
// Compiler implementation of the D programming language
// Copyright (c) 1999-2009 by Digital Mars
// All Rights Reserved
// written by Walter Bright
// http://www.digitalmars.com
// License for redistribution is by either the Artistic License
// in artistic.txt, or the GNU General Public License in gnu.txt.
// See the included readme.txt for details.

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>

#include "../l_service/c_ds/rmem.h"

#include "statement.h"
#include "expression.h"
#include "cond.h"
#include "init.h"
#include "staticassert.h"
#include "mtype.h"
#include "scope.h"
#include "declaration.h"
#include "aggregate.h"
#include "../l_neo_lexer/id.h"
#include "hdrgen.h"
#include "parse.h"
#include "template.h"

/******************************** S_Statement ***************************/

S_Statement::S_Statement(Loc loc)
    : loc(loc)
{
#ifdef _DH
    // If this is an in{} contract scope statement (skip for determining
    //  inlineStatus of a function body for header content)
    incontract = 0;
#endif
}

S_Statement *S_Statement::syntaxCopy()
{
    assert(0);
    return NULL;
}

void S_Statement::oPrint()
{
    fprintf(stdmsg, "%s\n", oToChars());
    fflush(stdmsg);
}

char *S_Statement::oToChars()
{   OutBuffer *buf;
    HdrGenState hgs;

    buf = new OutBuffer();
    toCBuffer(buf, &hgs);
    return buf->oToChars();
}

void S_Statement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->printf("S_Statement::toCBuffer()");
    buf->writenl();
}

S_Statement *S_Statement::semantic(Scope *sc)
{
    return this;
}

// Same as semantic(), but do create a new scope

S_Statement *S_Statement::semanticScope(Scope *sc, S_Statement *sbreak, S_Statement *scontinue)
{   Scope *scd;
    S_Statement *s;

    scd = sc->push();
    if (sbreak)
	scd->sbreak = sbreak;
    if (scontinue)
	scd->scontinue = scontinue;
    s = semantic(scd);
    scd->pop();
    return s;
}

void S_Statement::error(const char *format, ...)
{
    va_list ap;
    va_start(ap, format);
    ::verror(loc, format, ap);
    va_end( ap );
}

void S_Statement::warning(const char *format, ...)
{
    if (global.params.warnings && !global.gag)
    {
	fprintf(stdmsg, "warning - ");
	va_list ap;
	va_start(ap, format);
	::verror(loc, format, ap);
	va_end( ap );
    }
}

int S_Statement::hasBreak()
{
    //printf("S_Statement::hasBreak()\n");
    return FALSE;
}

int S_Statement::hasContinue()
{
    return FALSE;
}

// TRUE if statement uses exception handling

int S_Statement::usesEH()
{
    return FALSE;
}

/* Only valid after semantic analysis
 */
int S_Statement::blockExit()
{
    printf("S_Statement::blockExit(%p)\n", this);
    printf("%s\n", oToChars());
    assert(0);
    return BEany;
}

// TRUE if statement 'comes from' somewhere else, like a goto

int S_Statement::comeFrom()
{
    //printf("S_Statement::comeFrom()\n");
    return FALSE;
}

/****************************************
 * If this statement has code that needs to run in a finally clause
 * at the end of the current scope, return that code in the form of
 * a S_Statement.
 * Output:
 *	*sentry		code executed upon entry to the scope
 *	*sexception	code executed upon exit from the scope via exception
 *	*sfinally	code executed in finally block
 */

void S_Statement::scopeCode(Scope *sc, S_Statement **sentry, S_Statement **sexception, S_Statement **sfinally)
{
    //printf("S_Statement::scopeCode()\n");
    //oPrint();
    *sentry = NULL;
    *sexception = NULL;
    *sfinally = NULL;
}

/*********************************
 * Flatten out the scope by presenting the statement
 * as an array of statements.
 * Returns NULL if no flattening necessary.
 */

Statements *S_Statement::flatten(Scope *sc)
{
    return NULL;
}


/******************************** S_ExpStatement ***************************/

S_ExpStatement::S_ExpStatement(Loc loc, E_Expression *exp)
    : S_Statement(loc)
{
    this->exp = exp;
}

S_Statement *S_ExpStatement::syntaxCopy()
{
    E_Expression *e = exp ? exp->syntaxCopy() : NULL;
    S_ExpStatement *es = new S_ExpStatement(loc, e);
    return es;
}

void S_ExpStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    if (exp)
	exp->toCBuffer(buf, hgs);
    buf->writeByte(';');
    if (!hgs->FLinit.init)
        buf->writenl();
}

S_Statement *S_ExpStatement::semantic(Scope *sc)
{
    if (exp)
    {
	//printf("S_ExpStatement::semantic() %s\n", exp->oToChars());
	exp = exp->semantic(sc);
	exp = resolveProperties(sc, exp);
	exp->checkSideEffect(0);
	exp = exp->optimize(0);
	if (exp->op == LT::TOKdeclaration && !isDeclarationStatement())
	{   S_Statement *s = new S_DeclarationStatement(loc, exp);
	    return s;
	}
	//exp = exp->optimize(isDeclarationStatement() ? WANTvalue : 0);
    }
    return this;
}

int S_ExpStatement::blockExit()
{   int result = BEfallthru;

    if (exp)
    {
	if (exp->op == LT::TOKhalt)
	    return BEhalt;
	if (exp->op == LT::TOKassert)
	{   E_AssertExp *a = (E_AssertExp *)exp;

	    if (a->e1->isBool(FALSE))	// if it's an assert(0)
		return BEhalt;
	}
	if (exp->canThrow())
	    result |= BEthrow;
    }
    return result;
}


/******************************** S_CompileStatement ***************************/

S_CompileStatement::S_CompileStatement(Loc loc, E_Expression *exp)
    : S_Statement(loc)
{
    this->exp = exp;
}

S_Statement *S_CompileStatement::syntaxCopy()
{
    E_Expression *e = exp->syntaxCopy();
    S_CompileStatement *es = new S_CompileStatement(loc, e);
    return es;
}

void S_CompileStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("mixin(");
    exp->toCBuffer(buf, hgs);
    buf->writestring(");");
    if (!hgs->FLinit.init)
        buf->writenl();
}

Statements *S_CompileStatement::flatten(Scope *sc)
{
    //printf("S_CompileStatement::flatten() %s\n", exp->oToChars());
    exp = exp->semantic(sc);
    exp = resolveProperties(sc, exp);
    exp = exp->optimize(WANTvalue | WANTinterpret);
    if (exp->op != LT::TOKstring)
    {	error("argument to mixin must be a string, not (%s)", exp->oToChars());
	return NULL;
    }
    E_StringExp *se = (E_StringExp *)exp;
    se = se->toUTF8(sc);
    Parser p(sc->module, (unsigned char *)se->string, se->len, 0);
    p.loc = loc;
    p.nextToken();

    Statements *a = new Statements();
    while (p.token.value != LT::TOKeof)
    {
	S_Statement *s = p.parseStatement(PSsemi | PScurlyscope);
	a->push(s);
    }
    return a;
}

S_Statement *S_CompileStatement::semantic(Scope *sc)
{
    //printf("S_CompileStatement::semantic() %s\n", exp->oToChars());
    Statements *a = flatten(sc);
    if (!a)
	return NULL;
    S_Statement *s = new S_CompoundStatement(loc, a);
    return s->semantic(sc);
}


/******************************** S_DeclarationStatement ***************************/

S_DeclarationStatement::S_DeclarationStatement(Loc loc, P_Dsymbol *declaration)
    : S_ExpStatement(loc, new E_DeclarationExp(loc, declaration))
{
}

S_DeclarationStatement::S_DeclarationStatement(Loc loc, E_Expression *exp)
    : S_ExpStatement(loc, exp)
{
}

S_Statement *S_DeclarationStatement::syntaxCopy()
{
    S_DeclarationStatement *ds = new S_DeclarationStatement(loc, exp->syntaxCopy());
    return ds;
}

void S_DeclarationStatement::scopeCode(Scope *sc, S_Statement **sentry, S_Statement **sexception, S_Statement **sfinally)
{
    //printf("S_DeclarationStatement::scopeCode()\n");
    //oPrint();

    *sentry = NULL;
    *sexception = NULL;
    *sfinally = NULL;

    if (exp)
    {
	if (exp->op == LT::TOKdeclaration)
	{
	    E_DeclarationExp *de = (E_DeclarationExp *)(exp);
	    P_VarDeclaration *v = de->declaration->isVarDeclaration();
	    if (v)
	    {	E_Expression *e;

		e = v->callAutoDtor(sc);
		if (e)
		{
		    //printf("dtor is: "); e->oPrint();
		    *sfinally = new S_ExpStatement(loc, e);
		}
	    }
	}
    }
}

void S_DeclarationStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    exp->toCBuffer(buf, hgs);
}


/******************************** S_CompoundStatement ***************************/

S_CompoundStatement::S_CompoundStatement(Loc loc, Statements *s)
    : S_Statement(loc)
{
    statements = s;
}

S_CompoundStatement::S_CompoundStatement(Loc loc, S_Statement *s1, S_Statement *s2)
    : S_Statement(loc)
{
    statements = new Statements();
    statements->reserve(2);
    statements->push(s1);
    statements->push(s2);
}

S_Statement *S_CompoundStatement::syntaxCopy()
{
    Statements *a = new Statements();
    a->setDim(statements->dim);
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *)statements->data[i];
	if (s)
	    s = s->syntaxCopy();
	a->data[i] = s;
    }
    S_CompoundStatement *cs = new S_CompoundStatement(loc, a);
    return cs;
}


S_Statement *S_CompoundStatement::semantic(Scope *sc)
{   S_Statement *s;

    //printf("S_CompoundStatement::semantic(this = %p, sc = %p)\n", this, sc);

    for (size_t i = 0; i < statements->dim; )
    {
	s = (S_Statement *) statements->data[i];
	if (s)
	{   Statements *a = s->flatten(sc);

	    if (a)
	    {
		statements->remove(i);
		statements->insert(i, a);
		continue;
	    }
	    s = s->semantic(sc);
	    statements->data[i] = s;
	    if (s)
	    {
		S_Statement *sentry;
		S_Statement *sexception;
		S_Statement *sfinally;

		s->scopeCode(sc, &sentry, &sexception, &sfinally);
		if (sentry)
		{
		    sentry = sentry->semantic(sc);
		    statements->data[i] = sentry;
		}
		if (sexception)
		{
		    if (i + 1 == statements->dim && !sfinally)
		    {
#if 1
			sexception = sexception->semantic(sc);
#else
			statements->push(sexception);
			if (sfinally)
			    // Assume sexception does not throw
			    statements->push(sfinally);
#endif
		    }
		    else
		    {
			/* Rewrite:
			 *	s; s1; s2;
			 * As:
			 *	s;
			 *	try { s1; s2; }
			 *	catch (Object __o)
			 *	{ sexception; throw __o; }
			 */
			S_Statement *body;
			Statements *a = new Statements();

			for (int j = i + 1; j < statements->dim; j++)
			{
			    a->push(statements->data[j]);
			}
			body = new S_CompoundStatement(0, a);
			body = new S_ScopeStatement(0, body);

			Identifier *id = Lexer::uniqueId("__o");

			S_Statement *handler = new S_ThrowStatement(0, new E_IdentifierExp(0, id));
			handler = new S_CompoundStatement(0, sexception, handler);

			Array *catches = new Array();
			Catch *ctch = new Catch(0, NULL, id, handler);
			catches->push(ctch);
			s = new S_TryCatchStatement(0, body, catches);

			if (sfinally)
			    s = new S_TryFinallyStatement(0, s, sfinally);
			s = s->semantic(sc);
			statements->setDim(i + 1);
			statements->push(s);
			break;
		    }
		}
		else if (sfinally)
		{
		    if (0 && i + 1 == statements->dim)
		    {
			statements->push(sfinally);
		    }
		    else
		    {
			/* Rewrite:
			 *	s; s1; s2;
			 * As:
			 *	s; try { s1; s2; } finally { sfinally; }
			 */
			S_Statement *body;
			Statements *a = new Statements();

			for (int j = i + 1; j < statements->dim; j++)
			{
			    a->push(statements->data[j]);
			}
			body = new S_CompoundStatement(0, a);
			s = new S_TryFinallyStatement(0, body, sfinally);
			s = s->semantic(sc);
			statements->setDim(i + 1);
			statements->push(s);
			break;
		    }
		}
	    }
	}
	i++;
    }
    if (statements->dim == 1)
    {
	return (S_Statement *)statements->data[0];
    }
    return this;
}

Statements *S_CompoundStatement::flatten(Scope *sc)
{
    return statements;
}

S_ReturnStatement *S_CompoundStatement::isReturnStatement()
{
    S_ReturnStatement *rs = NULL;

    for (int i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s)
	{
	    rs = s->isReturnStatement();
	    if (rs)
		break;
	}
    }
    return rs;
}

void S_CompoundStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    for (int i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s)
	    s->toCBuffer(buf, hgs);
    }
}

int S_CompoundStatement::usesEH()
{
    for (int i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s && s->usesEH())
	    return TRUE;
    }
    return FALSE;
}

int S_CompoundStatement::blockExit()
{
    //printf("S_CompoundStatement::blockExit(%p) %d\n", this, statements->dim);
    int result = BEfallthru;
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s)
	{
//printf("result = x%x\n", result);
//printf("%s\n", s->oToChars());
	    if (!(result & BEfallthru) && !s->comeFrom())
	    {
		s->warning("statement is not reachable");
	    }

	    result &= ~BEfallthru;
	    result |= s->blockExit();
	}
    }
    return result;
}


int S_CompoundStatement::comeFrom()
{   int comefrom = FALSE;

    //printf("S_CompoundStatement::comeFrom()\n");
    for (int i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *)statements->data[i];

	if (!s)
	    continue;

	comefrom |= s->comeFrom();
    }
    return comefrom;
}


/**************************** S_UnrolledLoopStatement ***************************/

S_UnrolledLoopStatement::S_UnrolledLoopStatement(Loc loc, Statements *s)
    : S_Statement(loc)
{
    statements = s;
}

S_Statement *S_UnrolledLoopStatement::syntaxCopy()
{
    Statements *a = new Statements();
    a->setDim(statements->dim);
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *)statements->data[i];
	if (s)
	    s = s->syntaxCopy();
	a->data[i] = s;
    }
    S_UnrolledLoopStatement *cs = new S_UnrolledLoopStatement(loc, a);
    return cs;
}


S_Statement *S_UnrolledLoopStatement::semantic(Scope *sc)
{
    //printf("S_UnrolledLoopStatement::semantic(this = %p, sc = %p)\n", this, sc);

    sc->noctor++;
    Scope *scd = sc->push();
    scd->sbreak = this;
    scd->scontinue = this;

    for (size_t i = 0; i < statements->dim; i++)
    {
	S_Statement *s = (S_Statement *) statements->data[i];
	if (s)
	{
	    s = s->semantic(scd);
	    statements->data[i] = s;
	}
    }

    scd->pop();
    sc->noctor--;
    return this;
}

void S_UnrolledLoopStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("unrolled {");
    buf->writenl();

    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s;

	s = (S_Statement *) statements->data[i];
	if (s)
	    s->toCBuffer(buf, hgs);
    }

    buf->writeByte('}');
    buf->writenl();
}

int S_UnrolledLoopStatement::hasBreak()
{
    return TRUE;
}

int S_UnrolledLoopStatement::hasContinue()
{
    return TRUE;
}

int S_UnrolledLoopStatement::usesEH()
{
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s && s->usesEH())
	    return TRUE;
    }
    return FALSE;
}

int S_UnrolledLoopStatement::blockExit()
{
    int result = BEfallthru;
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *) statements->data[i];
	if (s)
	{
	    int r = s->blockExit();
	    result |= r & ~(BEbreak | BEcontinue);
	}
    }
    return result;
}


int S_UnrolledLoopStatement::comeFrom()
{   int comefrom = FALSE;

    //printf("S_UnrolledLoopStatement::comeFrom()\n");
    for (size_t i = 0; i < statements->dim; i++)
    {	S_Statement *s = (S_Statement *)statements->data[i];

	if (!s)
	    continue;

	comefrom |= s->comeFrom();
    }
    return comefrom;
}


/******************************** S_ScopeStatement ***************************/

S_ScopeStatement::S_ScopeStatement(Loc loc, S_Statement *s)
    : S_Statement(loc)
{
    this->statement = s;
}

S_Statement *S_ScopeStatement::syntaxCopy()
{
    S_Statement *s;

    s = statement ? statement->syntaxCopy() : NULL;
    s = new S_ScopeStatement(loc, s);
    return s;
}


S_Statement *S_ScopeStatement::semantic(Scope *sc)
{   P_ScopeDsymbol *sym;

    //printf("S_ScopeStatement::semantic(sc = %p)\n", sc);
    if (statement)
    {	Statements *a;

	sym = new P_ScopeDsymbol();
	sym->parent = sc->scopesym;
	sc = sc->push(sym);

	a = statement->flatten(sc);
	if (a)
	{
	    statement = new S_CompoundStatement(loc, a);
	}

	statement = statement->semantic(sc);
	if (statement)
	{
	    S_Statement *sentry;
	    S_Statement *sexception;
	    S_Statement *sfinally;

	    statement->scopeCode(sc, &sentry, &sexception, &sfinally);
	    if (sfinally)
	    {
		//printf("adding sfinally\n");
		statement = new S_CompoundStatement(loc, statement, sfinally);
	    }
	}

	sc->pop();
    }
    return this;
}

int S_ScopeStatement::hasBreak()
{
    //printf("S_ScopeStatement::hasBreak() %s\n", oToChars());
    return statement ? statement->hasBreak() : FALSE;
}

int S_ScopeStatement::hasContinue()
{
    return statement ? statement->hasContinue() : FALSE;
}

int S_ScopeStatement::usesEH()
{
    return statement ? statement->usesEH() : FALSE;
}

int S_ScopeStatement::blockExit()
{
    //printf("S_ScopeStatement::blockExit(%p)\n", statement);
    return statement ? statement->blockExit() : BEfallthru;
}


int S_ScopeStatement::comeFrom()
{
    //printf("S_ScopeStatement::comeFrom()\n");
    return statement ? statement->comeFrom() : FALSE;
}

void S_ScopeStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writeByte('{');
    buf->writenl();

    if (statement)
	statement->toCBuffer(buf, hgs);

    buf->writeByte('}');
    buf->writenl();
}

/******************************** S_WhileStatement ***************************/

S_WhileStatement::S_WhileStatement(Loc loc, E_Expression *c, S_Statement *b)
    : S_Statement(loc)
{
    condition = c;
    body = b;
}

S_Statement *S_WhileStatement::syntaxCopy()
{
    S_WhileStatement *s = new S_WhileStatement(loc, condition->syntaxCopy(), body ? body->syntaxCopy() : NULL);
    return s;
}


S_Statement *S_WhileStatement::semantic(Scope *sc)
{
#if 0
    if (condition->op == LT::TOKmatch)
    {
	/* Rewrite while (condition) body as:
	 *   if (condition)
	 *     do
	 *       body
	 *     while ((_match = _match.opNext), _match);
	 */

	Expression *ew = new IdentifierExp(0, Id::_match);
	ew = new DotIdExp(0, ew, Id::next);
	ew = new AssignExp(0, new IdentifierExp(0, Id::_match), ew);
	////ew = new EqualExp(LT::TOKnotequal, 0, ew, new NullExp(0));
	Expression *ev = new IdentifierExp(0, Id::_match);
	//ev = new E_CastExp(0, ev, Type::tvoidptr);
	ew = new CommaExp(0, ew, ev);
	Statement *sw = new DoStatement(loc, body, ew);
	Statement *si = new IfStatement(loc, condition, sw, NULL);
	return si->semantic(sc);
    }
#endif

    condition = condition->semantic(sc);
    condition = resolveProperties(sc, condition);
    condition = condition->optimize(WANTvalue);
    condition = condition->checkToBoolean();

    sc->noctor++;

    Scope *scd = sc->push();
    scd->sbreak = this;
    scd->scontinue = this;
    if (body)
	body = body->semantic(scd);
    scd->pop();

    sc->noctor--;

    return this;
}

int S_WhileStatement::hasBreak()
{
    return TRUE;
}

int S_WhileStatement::hasContinue()
{
    return TRUE;
}

int S_WhileStatement::usesEH()
{
    return body ? body->usesEH() : 0;
}

int S_WhileStatement::blockExit()
{
    //printf("S_WhileStatement::blockExit(%p)\n", this);

    int result = BEnone;
    if (condition->canThrow())
	result |= BEthrow;
    if (condition->isBool(TRUE))
    {
	if (body)
	{   result |= body->blockExit();
	    if (result & BEbreak)
		result |= BEfallthru;
	}
    }
    else if (condition->isBool(FALSE))
    {
	result |= BEfallthru;
    }
    else
    {
	if (body)
	    result |= body->blockExit();
	result |= BEfallthru;
    }
    result &= ~(BEbreak | BEcontinue);
    return result;
}


int S_WhileStatement::comeFrom()
{
    if (body)
	return body->comeFrom();
    return FALSE;
}

void S_WhileStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("while (");
    condition->toCBuffer(buf, hgs);
    buf->writebyte(')');
    buf->writenl();
    if (body)
	body->toCBuffer(buf, hgs);
}

/******************************** S_DoStatement ***************************/

S_DoStatement::S_DoStatement(Loc loc, S_Statement *b, E_Expression *c)
    : S_Statement(loc)
{
    body = b;
    condition = c;
}

S_Statement *S_DoStatement::syntaxCopy()
{
    S_DoStatement *s = new S_DoStatement(loc, body ? body->syntaxCopy() : NULL, condition->syntaxCopy());
    return s;
}


S_Statement *S_DoStatement::semantic(Scope *sc)
{
    sc->noctor++;
    if (body)
	body = body->semanticScope(sc, this, this);
    sc->noctor--;
    condition = condition->semantic(sc);
    condition = resolveProperties(sc, condition);
    condition = condition->optimize(WANTvalue);

    condition = condition->checkToBoolean();

    return this;
}

int S_DoStatement::hasBreak()
{
    return TRUE;
}

int S_DoStatement::hasContinue()
{
    return TRUE;
}

int S_DoStatement::usesEH()
{
    return body ? body->usesEH() : 0;
}

int S_DoStatement::blockExit()
{   int result;

    if (body)
    {	result = body->blockExit();
	if (result == BEbreak)
	    return BEfallthru;
	if (result & BEcontinue)
	    result |= BEfallthru;
    }
    else
	result = BEfallthru;
    if (result & BEfallthru)
    {	if (condition->canThrow())
	    result |= BEthrow;
	if (!(result & BEbreak) && condition->isBool(TRUE))
	    result &= ~BEfallthru;
    }
    result &= ~(BEbreak | BEcontinue);
    return result;
}


int S_DoStatement::comeFrom()
{
    if (body)
	return body->comeFrom();
    return FALSE;
}

void S_DoStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("do");
    buf->writenl();
    if (body)
	body->toCBuffer(buf, hgs);
    buf->writestring("while (");
    condition->toCBuffer(buf, hgs);
    buf->writebyte(')');
}

/******************************** S_ForStatement ***************************/

S_ForStatement::S_ForStatement(Loc loc, S_Statement *init, E_Expression *condition, E_Expression *increment, S_Statement *body)
    : S_Statement(loc)
{
    this->init = init;
    this->condition = condition;
    this->increment = increment;
    this->body = body;
}

S_Statement *S_ForStatement::syntaxCopy()
{
    S_Statement *i = NULL;
    if (init)
	i = init->syntaxCopy();
    E_Expression *c = NULL;
    if (condition)
	c = condition->syntaxCopy();
    E_Expression *inc = NULL;
    if (increment)
	inc = increment->syntaxCopy();
    S_ForStatement *s = new S_ForStatement(loc, i, c, inc, body->syntaxCopy());
    return s;
}

S_Statement *S_ForStatement::semantic(Scope *sc)
{
    P_ScopeDsymbol *sym = new P_ScopeDsymbol();
    sym->parent = sc->scopesym;
    sc = sc->push(sym);
    if (init)
	init = init->semantic(sc);
    sc->noctor++;
    if (condition)
    {
	condition = condition->semantic(sc);
	condition = resolveProperties(sc, condition);
	condition = condition->optimize(WANTvalue);
	condition = condition->checkToBoolean();
    }
    if (increment)
    {	increment = increment->semantic(sc);
	increment = resolveProperties(sc, increment);
    }

    sc->sbreak = this;
    sc->scontinue = this;
    body = body->semantic(sc);
    sc->noctor--;

    sc->pop();
    return this;
}

void S_ForStatement::scopeCode(Scope *sc, S_Statement **sentry, S_Statement **sexception, S_Statement **sfinally)
{
    //printf("S_ForStatement::scopeCode()\n");
    //oPrint();
    if (init)
	init->scopeCode(sc, sentry, sexception, sfinally);
    else
	S_Statement::scopeCode(sc, sentry, sexception, sfinally);
}

int S_ForStatement::hasBreak()
{
    //printf("S_ForStatement::hasBreak()\n");
    return TRUE;
}

int S_ForStatement::hasContinue()
{
    return TRUE;
}

int S_ForStatement::usesEH()
{
    return (init && init->usesEH()) || body->usesEH();
}

int S_ForStatement::blockExit()
{   int result = BEfallthru;

    if (init)
    {	result = init->blockExit();
	if (!(result & BEfallthru))
	    return result;
    }
    if (condition)
    {	if (condition->canThrow())
	    result |= BEthrow;
    }
    else
	result &= ~BEfallthru;	// the body must do the exiting
    if (body)
    {	int r = body->blockExit();
	if (r & (BEbreak | BEgoto))
	    result |= BEfallthru;
	result |= r & ~(BEfallthru | BEbreak | BEcontinue);
    }
    if (increment && increment->canThrow())
	result |= BEthrow;
    return result;
}


int S_ForStatement::comeFrom()
{
    //printf("S_ForStatement::comeFrom()\n");
    if (body)
    {	int result = body->comeFrom();
	//printf("result = %d\n", result);
	return result;
    }
    return FALSE;
}

void S_ForStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("for (");
    if (init)
    {
        hgs->FLinit.init++;
        hgs->FLinit.decl = 0;
        init->toCBuffer(buf, hgs);
        if (hgs->FLinit.decl > 0)
            buf->writebyte(';');
        hgs->FLinit.decl = 0;
        hgs->FLinit.init--;
    }
    else
        buf->writebyte(';');
    if (condition)
    {   buf->writebyte(' ');
        condition->toCBuffer(buf, hgs);
    }
    buf->writebyte(';');
    if (increment)
    {   buf->writebyte(' ');
        increment->toCBuffer(buf, hgs);
    }
    buf->writebyte(')');
    buf->writenl();
    buf->writebyte('{');
    buf->writenl();
    body->toCBuffer(buf, hgs);
    buf->writebyte('}');
    buf->writenl();
}

/******************************** S_ForeachStatement ***************************/

S_ForeachStatement::S_ForeachStatement(Loc loc, LT::T op, Arguments *arguments,
	E_Expression *aggr, S_Statement *body)
    : S_Statement(loc)
{
    this->op = op;
    this->arguments = arguments;
    this->aggr = aggr;
    this->body = body;

    this->key = NULL;
    this->value = NULL;

    this->func = NULL;
}

S_Statement *S_ForeachStatement::syntaxCopy()
{
    Arguments *args = Argument::arraySyntaxCopy(arguments);
    E_Expression *exp = aggr->syntaxCopy();
    S_ForeachStatement *s = new S_ForeachStatement(loc, op, args, exp,
	body ? body->syntaxCopy() : NULL);
    return s;
}

S_Statement *S_ForeachStatement::semantic(Scope *sc)
{
    //printf("S_ForeachStatement::semantic() %p\n", this);
    P_ScopeDsymbol *sym;
    S_Statement *s = this;
    size_t dim = arguments->dim;
    TypeAArray *taa = NULL;

    Type *tn = NULL;
    Type *tnv = NULL;

    func = sc->func;
    if (func->fes)
	func = func->fes->func;

    aggr = aggr->semantic(sc);
    aggr = resolveProperties(sc, aggr);
    aggr = aggr->optimize(WANTvalue);
    if (!aggr->type)
    {
	error("invalid foreach aggregate %s", aggr->oToChars());
	return this;
    }

    inferApplyArgTypes(op, arguments, aggr);

    /* Check for inference errors
     */
    if (dim != arguments->dim)
    {
	//printf("dim = %d, arguments->dim = %d\n", dim, arguments->dim);
	error("cannot uniquely infer foreach argument types");
	return this;
    }

    Type *tab = aggr->type->toBasetype();

    if (tab->ty == Ttuple)	// don't generate new scope for tuple loops
    {
	if (dim < 1 || dim > 2)
	{
	    error("only one (value) or two (key,value) arguments for tuple foreach");
	    return s;
	}

	TypeTuple *tuple = (TypeTuple *)tab;
	Statements *statements = new Statements();
	//printf("aggr: op = %d, %s\n", aggr->op, aggr->oToChars());
	size_t n;
	E_TupleExp *te = NULL;
	if (aggr->op == LT::TOKtuple)	// expression tuple
	{   te = (E_TupleExp *)aggr;
	    n = te->exps->dim;
	}
	else if (aggr->op == LT::TOKtype)	// type tuple
	{
	    n = Argument::dim(tuple->arguments);
	}
	else
	    assert(0);
	for (size_t j = 0; j < n; j++)
	{   size_t k = (op == LT::TOKforeach) ? j : n - 1 - j;
	    E_Expression *e;
	    Type *t;
	    if (te)
		e = (E_Expression *)te->exps->data[k];
	    else
		t = Argument::getNth(tuple->arguments, k)->type;
	    Argument *arg = (Argument *)arguments->data[0];
	    Statements *st = new Statements();

	    if (dim == 2)
	    {   // Declare key
		if (arg->storageClass & (STCout | STCref | STClazy))
		    error("no storage class for key %s", arg->ident->oToChars());
		TY keyty = arg->type->ty;
		if ((keyty != Tint32 && keyty != Tuns32) ||
		    (global.params.isX86_64 &&
			    keyty != Tint64 && keyty != Tuns64)
		   )
		{
		    error("foreach: key type must be int or uint, not %s", arg->type->oToChars());
		}
		Initializer *ie = new ExpInitializer(0, new E_IntegerExp(k));
		P_VarDeclaration *var = new P_VarDeclaration(loc, arg->type, arg->ident, ie);
		var->storage_class |= STCmanifest;
		E_DeclarationExp *de = new E_DeclarationExp(loc, var);
		st->push(new S_ExpStatement(loc, de));
		arg = (Argument *)arguments->data[1];	// value
	    }
	    // Declare value
	    if (arg->storageClass & (STCout | STCref | STClazy))
		error("no storage class for value %s", arg->ident->oToChars());
	    P_Dsymbol *var;
	    if (te)
	    {	Type *tb = e->type->toBasetype();
		if ((tb->ty == Tfunction || tb->ty == Tsarray) && e->op == LT::TOKvar)
		{   E_VarExp *ve = (E_VarExp *)e;
		    var = new P_AliasDeclaration(loc, arg->ident, ve->var);
		}
		else
		{
		    arg->type = e->type;
		    Initializer *ie = new ExpInitializer(0, e);
		    P_VarDeclaration *v = new P_VarDeclaration(loc, arg->type, arg->ident, ie);
		    if (e->isConst())
			v->storage_class |= STCconst;
		    var = v;
		}
	    }
	    else
	    {
		var = new P_AliasDeclaration(loc, arg->ident, t);
	    }
	    E_DeclarationExp *de = new E_DeclarationExp(loc, var);
	    st->push(new S_ExpStatement(loc, de));

	    st->push(body->syntaxCopy());
	    s = new S_CompoundStatement(loc, st);
	    s = new S_ScopeStatement(loc, s);
	    statements->push(s);
	}

	s = new S_UnrolledLoopStatement(loc, statements);
	s = s->semantic(sc);
	return s;
    }

    sym = new P_ScopeDsymbol();
    sym->parent = sc->scopesym;
    sc = sc->push(sym);

    sc->noctor++;

    switch (tab->ty)
    {
	case Tarray:
	case Tsarray:
	    if (!checkForArgTypes())
		return this;

	    if (dim < 1 || dim > 2)
	    {
		error("only one or two arguments for array foreach");
		break;
	    }

	    /* Look for special case of parsing char types out of char type
	     * array.
	     */
	    tn = tab->nextOf()->toBasetype();
	    if (tn->ty == Tchar || tn->ty == Twchar || tn->ty == Tdchar)
	    {	Argument *arg;

		int i = (dim == 1) ? 0 : 1;	// index of value
		arg = (Argument *)arguments->data[i];
		arg->type = arg->type->semantic(loc, sc);
		tnv = arg->type->toBasetype();
		if (tnv->ty != tn->ty &&
		    (tnv->ty == Tchar || tnv->ty == Twchar || tnv->ty == Tdchar))
		{
		    if (arg->storageClass & STCref)
			error("foreach: value of UTF conversion cannot be ref");
		    if (dim == 2)
		    {	arg = (Argument *)arguments->data[0];
			if (arg->storageClass & STCref)
			    error("foreach: key cannot be ref");
		    }
		    goto Lapply;
		}
	    }

	    for (size_t i = 0; i < dim; i++)
	    {	// Declare args
		Argument *arg = (Argument *)arguments->data[i];
		P_VarDeclaration *var;

		var = new P_VarDeclaration(loc, arg->type, arg->ident, NULL);
		var->storage_class |= STCforeach;
		var->storage_class |= arg->storageClass & (STCin | STCout | STCref | STCconst | STCinvariant);
		if (dim == 2 && i == 0)
		{   key = var;
		    //var->storage_class |= STCfinal;
		}
		else
		{
		    value = var;
		    /* Reference to immutable data should be marked as const
		     */
		    if (var->storage_class & STCref && !tn->isMutable())
		    {
			var->storage_class |= STCconst;
		    }
		}
#if 1
		E_DeclarationExp *de = new E_DeclarationExp(loc, var);
		de->semantic(sc);
#else
		var->semantic(sc);
		if (!sc->insert(var))
		    error("%s already defined", var->ident->oToChars());
#endif
	    }

	    sc->sbreak = this;
	    sc->scontinue = this;
	    body = body->semantic(sc);

	    if (tab->nextOf()->implicitConvTo(value->type) < MATCHconst)
	    {
		if (aggr->op == LT::TOKstring)
		    aggr = aggr->implicitCastTo(sc, value->type->arrayOf());
		else
		    error("foreach: %s is not an array of %s",
			tab->oToChars(), value->type->oToChars());
	    }

	    if (key &&
		((key->type->ty != Tint32 && key->type->ty != Tuns32) ||
		 (global.params.isX86_64 &&
			key->type->ty != Tint64 && key->type->ty != Tuns64)
	        )
	       )
	    {
		error("foreach: key type must be int or uint, not %s", key->type->oToChars());
	    }

	    if (key && key->storage_class & (STCout | STCref))
		error("foreach: key cannot be out or ref");
	    break;

	case Taarray:
	    if (!checkForArgTypes())
		return this;

	    taa = (TypeAArray *)tab;
	    if (dim < 1 || dim > 2)
	    {
		error("only one or two arguments for associative array foreach");
		break;
	    }
	    if (op == LT::TOKforeach_reverse)
	    {
		error("no reverse iteration on associative arrays");
	    }
	    goto Lapply;

	case Tclass:
	case Tstruct:
#if V2
	{   /* Look for range iteration, i.e. the properties
	     * .empty, .next, .retreat, .head and .rear
	     *    foreach (e; range) { ... }
	     * translates to:
	     *    for (auto __r = range; !__r.empty; __r.next)
	     *    {   auto e = __r.head;
	     *        ...
	     *    }
	     */
	    if (dim != 1)	// only one argument allowed with ranges
		goto Lapply;
	    P_AggregateDeclaration *ad = (tab->ty == Tclass)
			? (P_AggregateDeclaration *)((TypeClass  *)tab)->sym
			: (P_AggregateDeclaration *)((TypeStruct *)tab)->sym;
	    Identifier *idhead;
	    Identifier *idnext;
	    if (op == LT::TOKforeach)
	    {	idhead = Id::Fhead;
		idnext = Id::Fnext;
	    }
	    else
	    {	idhead = Id::Ftoe;
		idnext = Id::Fretreat;
	    }
	    P_Dsymbol *shead = search_function(ad, idhead);
	    if (!shead)
		goto Lapply;

	    /* Generate a temporary __r and initialize it with the aggregate.
	     */
	    Identifier *id = Identifier::generateId("__r");
	    P_VarDeclaration *r = new P_VarDeclaration(loc, NULL, id, new ExpInitializer(loc, aggr));
//	    r->semantic(sc);
//printf("r: %s, init: %s\n", r->oToChars(), r->init->oToChars());
	    S_Statement *init = new S_DeclarationStatement(loc, r);
//printf("init: %s\n", init->oToChars());

	    // !__r.empty
	    E_Expression *e = new E_VarExp(loc, r);
	    e = new E_DotIdExp(loc, e, Id::Fempty);
	    E_Expression *condition = new E_NotExp(loc, e);

	    // __r.next
	    e = new E_VarExp(loc, r);
	    E_Expression *increment = new E_DotIdExp(loc, e, idnext);

	    /* Declaration statement for e:
	     *    auto e = __r.idhead;
	     */
	    e = new E_VarExp(loc, r);
	    E_Expression *einit = new E_DotIdExp(loc, e, idhead);
//	    einit = einit->semantic(sc);
	    Argument *arg = (Argument *)arguments->data[0];
	    P_VarDeclaration *ve = new P_VarDeclaration(loc, arg->type, arg->ident, new ExpInitializer(loc, einit));
	    ve->storage_class |= STCforeach;
	    ve->storage_class |= arg->storageClass & (STCin | STCout | STCref | STCconst | STCinvariant);

	    E_DeclarationExp *de = new E_DeclarationExp(loc, ve);

	    S_Statement *body = new S_CompoundStatement(loc,
		new S_DeclarationStatement(loc, de), this->body);

	    s = new S_ForStatement(loc, init, condition, increment, body);
	    s = s->semantic(sc);
	    break;
	}
#endif
	case Tdelegate:
	Lapply:
	{   P_FuncDeclaration *fdapply;
	    Arguments *args;
	    E_Expression *ec;
	    E_Expression *e;
	    P_FuncLiteralDeclaration *fld;
	    Argument *a;
	    Type *t;
	    E_Expression *flde;
	    Identifier *id;
	    Type *tret;

	    if (!checkForArgTypes())
		return this;

	    tret = func->type->nextOf();

	    // Need a variable to hold value from any return statements in body.
	    if (!sc->func->vresult && tret && tret != Type::tvoid)
	    {	P_VarDeclaration *v;

		v = new P_VarDeclaration(loc, tret, Id::result, NULL);
		v->noauto = 1;
		v->semantic(sc);
		if (!sc->insert(v))
		    assert(0);
		v->parent = sc->func;
		sc->func->vresult = v;
	    }

	    /* Turn body into the function literal:
	     *	int delegate(ref T arg) { body }
	     */
	    args = new Arguments();
	    for (size_t i = 0; i < dim; i++)
	    {	Argument *arg = (Argument *)arguments->data[i];

		arg->type = arg->type->semantic(loc, sc);
		if (arg->storageClass & STCref)
		    id = arg->ident;
		else
		{   // Make a copy of the ref argument so it isn't
		    // a reference.
		    P_VarDeclaration *v;
		    Initializer *ie;

		    id = Lexer::uniqueId("__applyArg", i);

		    ie = new ExpInitializer(0, new E_IdentifierExp(0, id));
		    v = new P_VarDeclaration(0, arg->type, arg->ident, ie);
		    s = new S_DeclarationStatement(0, v);
		    body = new S_CompoundStatement(loc, s, body);
		}
		a = new Argument(STCref, arg->type, id, NULL);
		args->push(a);
	    }
	    t = new TypeFunction(args, Type::tint32, 0, LINKd);
	    fld = new P_FuncLiteralDeclaration(loc, 0, t, LT::TOKdelegate, this);
	    fld->fbody = body;
	    flde = new E_FuncExp(loc, fld);
	    flde = flde->semantic(sc);
	    fld->tookAddressOf = 0;

	    // Resolve any forward referenced goto's
	    for (int i = 0; i < gotos.dim; i++)
	    {	S_CompoundStatement *cs = (S_CompoundStatement *)gotos.data[i];
		S_GotoStatement *gs = (S_GotoStatement *)cs->statements->data[0];

		if (!gs->label->statement)
		{   // 'Promote' it to this scope, and replace with a return
		    cases.push(gs);
		    s = new S_ReturnStatement(0, new E_IntegerExp(cases.dim + 1));
		    cs->statements->data[0] = (void *)s;
		}
	    }

	    if (tab->ty == Taarray)
	    {
		// Check types
		Argument *arg = (Argument *)arguments->data[0];
		if (dim == 2)
		{
		    if (arg->storageClass & STCref)
			error("foreach: index cannot be ref");
		    if (!arg->type->oEquals(taa->index))
			error("foreach: index must be type %s, not %s", taa->index->oToChars(), arg->type->oToChars());
		    arg = (Argument *)arguments->data[1];
		}
		if (!arg->type->oEquals(taa->nextOf()))
		    error("foreach: value must be type %s, not %s", taa->nextOf()->oToChars(), arg->type->oToChars());

		/* Call:
		 *	_aaApply(aggr, keysize, flde)
		 */
		if (dim == 2)
		    fdapply = P_FuncDeclaration::genCfunc(Type::tindex, "_aaApply2");
		else
		    fdapply = P_FuncDeclaration::genCfunc(Type::tindex, "_aaApply");
		ec = new E_VarExp(0, fdapply);
		Expressions *exps = new Expressions();
		exps->push(aggr);
		size_t keysize = taa->index->size();
		keysize = (keysize + 3) & ~3;
		exps->push(new E_IntegerExp(0, keysize, Type::tint32));
		exps->push(flde);
		e = new E_CallExp(loc, ec, exps);
		e->type = Type::tindex;	// don't run semantic() on e
	    }
	    else if (tab->ty == Tarray || tab->ty == Tsarray)
	    {
		/* Call:
		 *	_aApply(aggr, flde)
		 */
		static char fntab[9][3] =
		{ "cc","cw","cd",
		  "wc","cc","wd",
		  "dc","dw","dd"
		};
		char fdname[7+1+2+ sizeof(dim)*3 + 1];
		int flag;

		switch (tn->ty)
		{
		    case Tchar:		flag = 0; break;
		    case Twchar:	flag = 3; break;
		    case Tdchar:	flag = 6; break;
		    default:		assert(0);
		}
		switch (tnv->ty)
		{
		    case Tchar:		flag += 0; break;
		    case Twchar:	flag += 1; break;
		    case Tdchar:	flag += 2; break;
		    default:		assert(0);
		}
		const char *r = (op == LT::TOKforeach_reverse) ? "R" : "";
		int j = sprintf(fdname, "_aApply%s%.*s%d", r, 2, fntab[flag], dim);
		assert(j < sizeof(fdname));
		fdapply = P_FuncDeclaration::genCfunc(Type::tindex, fdname);

		ec = new E_VarExp(0, fdapply);
		Expressions *exps = new Expressions();
		if (tab->ty == Tsarray)
		   aggr = aggr->castTo(sc, tn->arrayOf());
		exps->push(aggr);
		exps->push(flde);
		e = new E_CallExp(loc, ec, exps);
		e->type = Type::tindex;	// don't run semantic() on e
	    }
	    else if (tab->ty == Tdelegate)
	    {
		/* Call:
		 *	aggr(flde)
		 */
		Expressions *exps = new Expressions();
		exps->push(flde);
		e = new E_CallExp(loc, aggr, exps);
		e = e->semantic(sc);
		if (e->type != Type::tint32)
		    error("opApply() function for %s must return an int", tab->oToChars());
	    }
	    else
	    {
		assert(tab->ty == Tstruct || tab->ty == Tclass);
		Identifier *idapply = (op == LT::TOKforeach_reverse)
				? Id::applyReverse : Id::apply;
		P_Dsymbol *sapply = search_function((P_AggregateDeclaration *)tab->toDsymbol(sc), idapply);
	        Expressions *exps = new Expressions();
#if 0
		TemplateDeclaration *td;
		if (sapply &&
		    (td = sapply->isTemplateDeclaration()) != NULL)
		{   /* Call:
		     *	aggr.apply!(fld)()
		     */
		    TemplateInstance *ti = new TemplateInstance(loc, idapply);
		    Objects *tiargs = new Objects();
		    tiargs->push(fld);
		    ti->tiargs = tiargs;
		    ec = new DotTemplateInstanceExp(loc, aggr, ti);
		}
		else
#endif
		{
		    /* Call:
		     *	aggr.apply(flde)
		     */
		    ec = new E_DotIdExp(loc, aggr, idapply);
		    exps->push(flde);
		}
		e = new E_CallExp(loc, ec, exps);
		e = e->semantic(sc);
		if (e->type != Type::tint32)
		    error("opApply() function for %s must return an int", tab->oToChars());
	    }

	    if (!cases.dim)
		// Easy case, a clean exit from the loop
		s = new S_ExpStatement(loc, e);
	    else
	    {	// Construct a switch statement around the return value
		// of the apply function.
		Statements *a = new Statements();

		// default: break; takes care of cases 0 and 1
		s = new S_BreakStatement(0, NULL);
		s = new S_DefaultStatement(0, s);
		a->push(s);

		// cases 2...
		for (int i = 0; i < cases.dim; i++)
		{
		    s = (S_Statement *)cases.data[i];
		    s = new S_CaseStatement(0, new E_IntegerExp(i + 2), s);
		    a->push(s);
		}

		s = new S_CompoundStatement(loc, a);
		s = new S_SwitchStatement(loc, e, s);
		s = s->semantic(sc);
	    }
	    break;
	}

	default:
	    error("foreach: %s is not an aggregate type", aggr->type->oToChars());
	    break;
    }
    sc->noctor--;
    sc->pop();
    return s;
}

bool S_ForeachStatement::checkForArgTypes()
{
    for (size_t i = 0; i < arguments->dim; i++)
    {	Argument *arg = (Argument *)arguments->data[i];
	if (!arg->type)
	{
	    error("cannot infer type for %s", arg->ident->oToChars());
	    return FALSE;
	}
    }
    return TRUE;
}

int S_ForeachStatement::hasBreak()
{
    return TRUE;
}

int S_ForeachStatement::hasContinue()
{
    return TRUE;
}

int S_ForeachStatement::usesEH()
{
    return body->usesEH();
}

int S_ForeachStatement::blockExit()
{   int result = BEfallthru;

    if (aggr->canThrow())
	result |= BEthrow;

    if (body)
    {
	result |= body->blockExit() & ~(BEbreak | BEcontinue);
    }
    return result;
}


int S_ForeachStatement::comeFrom()
{
    if (body)
	return body->comeFrom();
    return FALSE;
}

void S_ForeachStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring(Token::toChars(op));
    buf->writestring(" (");
    for (int i = 0; i < arguments->dim; i++)
    {
	Argument *a = (Argument *)arguments->data[i];
	if (i)
	    buf->writestring(", ");
	if (a->storageClass & STCref)
	    buf->writestring((global.params.Dversion == 1)
		? (char*)"inout " : (char*)"ref ");
	if (a->type)
	    a->type->toCBuffer(buf, a->ident, hgs);
	else
	    buf->writestring(a->ident->oToChars());
    }
    buf->writestring("; ");
    aggr->toCBuffer(buf, hgs);
    buf->writebyte(')');
    buf->writenl();
    buf->writebyte('{');
    buf->writenl();
    if (body)
	body->toCBuffer(buf, hgs);
    buf->writebyte('}');
    buf->writenl();
}

/**************************** S_ForeachRangeStatement ***************************/

#if V2

S_ForeachRangeStatement::S_ForeachRangeStatement(Loc loc, LT::T op, Argument *arg,
	E_Expression *lwr, E_Expression *upr, S_Statement *body)
    : S_Statement(loc)
{
    this->op = op;
    this->arg = arg;
    this->lwr = lwr;
    this->upr = upr;
    this->body = body;

    this->key = NULL;
}

S_Statement *S_ForeachRangeStatement::syntaxCopy()
{
    S_ForeachRangeStatement *s = new S_ForeachRangeStatement(loc, op,
	arg->syntaxCopy(),
	lwr->syntaxCopy(),
	upr->syntaxCopy(),
	body ? body->syntaxCopy() : NULL);
    return s;
}

S_Statement *S_ForeachRangeStatement::semantic(Scope *sc)
{
    //printf("S_ForeachRangeStatement::semantic() %p\n", this);
    P_ScopeDsymbol *sym;
    S_Statement *s = this;

    lwr = lwr->semantic(sc);
    lwr = resolveProperties(sc, lwr);
    lwr = lwr->optimize(WANTvalue);
    if (!lwr->type)
    {
	error("invalid range lower bound %s", lwr->oToChars());
	return this;
    }

    upr = upr->semantic(sc);
    upr = resolveProperties(sc, upr);
    upr = upr->optimize(WANTvalue);
    if (!upr->type)
    {
	error("invalid range upper bound %s", upr->oToChars());
	return this;
    }

    if (arg->type)
    {
	arg->type = arg->type->semantic(loc, sc);
	lwr = lwr->implicitCastTo(sc, arg->type);
	upr = upr->implicitCastTo(sc, arg->type);
    }
    else
    {
	/* Must infer types from lwr and upr
	 */
	E_AddExp ea(loc, lwr, upr);
	ea.typeCombine(sc);
	arg->type = ea.type->mutableOf();
	lwr = ea.e1;
	upr = ea.e2;
    }
    if (!arg->type->isscalar())
	error("%s is not a scalar type", arg->type->oToChars());

    sym = new P_ScopeDsymbol();
    sym->parent = sc->scopesym;
    sc = sc->push(sym);

    sc->noctor++;

    key = new P_VarDeclaration(loc, arg->type, arg->ident, NULL);
    E_DeclarationExp *de = new E_DeclarationExp(loc, key);
    de->semantic(sc);

    if (key->storage_class)
	error("foreach range: key cannot have storage class");

    sc->sbreak = this;
    sc->scontinue = this;
    body = body->semantic(sc);

    sc->noctor--;
    sc->pop();
    return s;
}

int S_ForeachRangeStatement::hasBreak()
{
    return TRUE;
}

int S_ForeachRangeStatement::hasContinue()
{
    return TRUE;
}

int S_ForeachRangeStatement::usesEH()
{
    return body->usesEH();
}

int S_ForeachRangeStatement::blockExit()
{   int result = BEfallthru;

    if (lwr && lwr->canThrow())
	result |= BEthrow;
    else if (upr && upr->canThrow())
	result |= BEthrow;

    if (body)
    {
	result |= body->blockExit() & ~(BEbreak | BEcontinue);
    }
    return result;
}


int S_ForeachRangeStatement::comeFrom()
{
    if (body)
	return body->comeFrom();
    return FALSE;
}

void S_ForeachRangeStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring(Token::toChars(op));
    buf->writestring(" (");

    if (arg->type)
	arg->type->toCBuffer(buf, arg->ident, hgs);
    else
	buf->writestring(arg->ident->oToChars());

    buf->writestring("; ");
    lwr->toCBuffer(buf, hgs);
    buf->writestring(" .. ");
    upr->toCBuffer(buf, hgs);
    buf->writebyte(')');
    buf->writenl();
    buf->writebyte('{');
    buf->writenl();
    if (body)
	body->toCBuffer(buf, hgs);
    buf->writebyte('}');
    buf->writenl();
}

#endif

/******************************** S_IfStatement ***************************/

S_IfStatement::S_IfStatement(Loc loc, Argument *arg, E_Expression *condition, S_Statement *ifbody, S_Statement *elsebody)
    : S_Statement(loc)
{
    this->arg = arg;
    this->condition = condition;
    this->ifbody = ifbody;
    this->elsebody = elsebody;
    this->match = NULL;
}

S_Statement *S_IfStatement::syntaxCopy()
{
    S_Statement *i = NULL;
    if (ifbody)
        i = ifbody->syntaxCopy();

    S_Statement *e = NULL;
    if (elsebody)
	e = elsebody->syntaxCopy();

    Argument *a = arg ? arg->syntaxCopy() : NULL;
    S_IfStatement *s = new S_IfStatement(loc, a, condition->syntaxCopy(), i, e);
    return s;
}

S_Statement *S_IfStatement::semantic(Scope *sc)
{
    condition = condition->semantic(sc);
    condition = resolveProperties(sc, condition);
    condition = condition->checkToBoolean();

    // If we can short-circuit evaluate the if statement, don't do the
    // semantic analysis of the skipped code.
    // This feature allows a limited form of conditional compilation.
    condition = condition->optimize(WANTflags);

    // Evaluate at runtime
    unsigned cs0 = sc->callSuper;
    unsigned cs1;

    Scope *scd;
    if (arg)
    {	/* Declare arg, which we will set to be the
	 * result of condition.
	 */
	P_ScopeDsymbol *sym = new P_ScopeDsymbol();
	sym->parent = sc->scopesym;
	scd = sc->push(sym);

	Type *t = arg->type ? arg->type : condition->type;
	match = new P_VarDeclaration(loc, t, arg->ident, NULL);
	match->noauto = 1;
	match->semantic(scd);
	if (!scd->insert(match))
	    assert(0);
	match->parent = sc->func;

	/* Generate:
	 *  (arg = condition)
	 */
	E_VarExp *v = new E_VarExp(0, match);
	condition = new E_AssignExp(loc, v, condition);
	condition = condition->semantic(scd);
    }
    else
	scd = sc->push();
    ifbody = ifbody->semantic(scd);
    scd->pop();

    cs1 = sc->callSuper;
    sc->callSuper = cs0;
    if (elsebody)
	elsebody = elsebody->semanticScope(sc, NULL, NULL);
    sc->mergeCallSuper(loc, cs1);

    return this;
}

int S_IfStatement::usesEH()
{
    return (ifbody && ifbody->usesEH()) || (elsebody && elsebody->usesEH());
}

int S_IfStatement::blockExit()
{
    //printf("S_IfStatement::blockExit(%p)\n", this);

    int result = BEnone;
    if (condition->canThrow())
	result |= BEthrow;
    if (condition->isBool(TRUE))
    {
	if (ifbody)
	    result |= ifbody->blockExit();
	else
	    result |= BEfallthru;
    }
    else if (condition->isBool(FALSE))
    {
	if (elsebody)
	    result |= elsebody->blockExit();
	else
	    result |= BEfallthru;
    }
    else
    {
	if (ifbody)
	    result |= ifbody->blockExit();
	else
	    result |= BEfallthru;
	if (elsebody)
	    result |= elsebody->blockExit();
	else
	    result |= BEfallthru;
    }
    //printf("S_IfStatement::blockExit(%p) = x%x\n", this, result);
    return result;
}


void S_IfStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("if (");
    if (arg)
    {
	if (arg->type)
	    arg->type->toCBuffer(buf, arg->ident, hgs);
	else
	{   buf->writestring("auto ");
	    buf->writestring(arg->ident->oToChars());
	}
	buf->writestring(" = ");
    }
    condition->toCBuffer(buf, hgs);
    buf->writebyte(')');
    buf->writenl();
    ifbody->toCBuffer(buf, hgs);
    if (elsebody)
    {   buf->writestring("else");
        buf->writenl();
        elsebody->toCBuffer(buf, hgs);
    }
}

/******************************** S_ConditionalStatement ***************************/

S_ConditionalStatement::S_ConditionalStatement(Loc loc, Condition *condition, S_Statement *ifbody, S_Statement *elsebody)
    : S_Statement(loc)
{
    this->condition = condition;
    this->ifbody = ifbody;
    this->elsebody = elsebody;
}

S_Statement *S_ConditionalStatement::syntaxCopy()
{
    S_Statement *e = NULL;
    if (elsebody)
	e = elsebody->syntaxCopy();
    S_ConditionalStatement *s = new S_ConditionalStatement(loc,
		condition->syntaxCopy(), ifbody->syntaxCopy(), e);
    return s;
}

S_Statement *S_ConditionalStatement::semantic(Scope *sc)
{
    //printf("S_ConditionalStatement::semantic()\n");

    // If we can short-circuit evaluate the if statement, don't do the
    // semantic analysis of the skipped code.
    // This feature allows a limited form of conditional compilation.
    if (condition->include(sc, NULL))
    {
	ifbody = ifbody->semantic(sc);
	return ifbody;
    }
    else
    {
	if (elsebody)
	    elsebody = elsebody->semantic(sc);
	return elsebody;
    }
}

Statements *S_ConditionalStatement::flatten(Scope *sc)
{
    S_Statement *s;

    if (condition->include(sc, NULL))
	s = ifbody;
    else
	s = elsebody;

    Statements *a = new Statements();
    a->push(s);
    return a;
}

int S_ConditionalStatement::usesEH()
{
    return (ifbody && ifbody->usesEH()) || (elsebody && elsebody->usesEH());
}

int S_ConditionalStatement::blockExit()
{
    int result = ifbody->blockExit();
    if (elsebody)
	result |= elsebody->blockExit();
    return result;
}

void S_ConditionalStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    condition->toCBuffer(buf, hgs);
    buf->writenl();
    buf->writeByte('{');
    buf->writenl();
    if (ifbody)
	ifbody->toCBuffer(buf, hgs);
    buf->writeByte('}');
    buf->writenl();
    if (elsebody)
    {
	buf->writestring("else");
	buf->writenl();
	buf->writeByte('{');
	buf->writenl();
	elsebody->toCBuffer(buf, hgs);
	buf->writeByte('}');
	buf->writenl();
    }
    buf->writenl();
}


/******************************** S_PragmaStatement ***************************/

S_PragmaStatement::S_PragmaStatement(Loc loc, Identifier *ident, Expressions *args, S_Statement *body)
    : S_Statement(loc)
{
    this->ident = ident;
    this->args = args;
    this->body = body;
}

S_Statement *S_PragmaStatement::syntaxCopy()
{
    S_Statement *b = NULL;
    if (body)
	b = body->syntaxCopy();
    S_PragmaStatement *s = new S_PragmaStatement(loc,
		ident, E_Expression::arraySyntaxCopy(args), b);
    return s;
}

S_Statement *S_PragmaStatement::semantic(Scope *sc)
{   // Should be merged with PragmaDeclaration
    //printf("S_PragmaStatement::semantic() %s\n", oToChars());
    //printf("body = %p\n", body);
    if (ident == Id::msg)
    {
        if (args)
        {
            for (size_t i = 0; i < args->dim; i++)
            {
                E_Expression *e = (E_Expression *)args->data[i];

                e = e->semantic(sc);
		e = e->optimize(WANTvalue | WANTinterpret);
                if (e->op == LT::TOKstring)
                {
                    E_StringExp *se = (E_StringExp *)e;
                    fprintf(stdmsg, "%.*s", (int)se->len, se->string);
                }
                else
		    error("string expected for message, not '%s'", e->oToChars());
            }
            fprintf(stdmsg, "\n");
        }
    }
    else if (ident == Id::lib)
    {
#if 1
	/* Should this be allowed?
	 */
	error("pragma(lib) not allowed as statement");
#else
	if (!args || args->dim != 1)
	    error("string expected for library name");
	else
	{
	    E_Expression *e = (E_Expression *)args->data[0];

	    e = e->semantic(sc);
	    e = e->optimize(WANTvalue | WANTinterpret);
	    args->data[0] = (void *)e;
	    if (e->op != LT::TOKstring)
		error("string expected for library name, not '%s'", e->oToChars());
	    else if (global.params.verbose)
	    {
		E_StringExp *se = (E_StringExp *)e;
		char *name = (char *)mem.malloc(se->len + 1);
		memcpy(name, se->string, se->len);
		name[se->len] = 0;
		printf("library   %s\n", name);
		mem.free(name);
	    }
	}
#endif
    }
    else if (ident == Id::startaddress)
    {
	if (!args || args->dim != 1)
	    error("function name expected for start address");
	else
	{
	    E_Expression *e = (E_Expression *)args->data[0];
	    e = e->semantic(sc);
	    e = e->optimize(WANTvalue | WANTinterpret);
	    args->data[0] = (void *)e;
	    P_Dsymbol *sa = getDsymbol(e);
	    if (!sa || !sa->isFuncDeclaration())
		error("function name expected for start address, not '%s'", e->oToChars());
	    if (body)
	    {
		body = body->semantic(sc);
	    }
	    return this;
	}
    }
    else
        error("unrecognized pragma(%s)", ident->oToChars());

    if (body)
    {
	body = body->semantic(sc);
    }
    return body;
}

int S_PragmaStatement::usesEH()
{
    return body && body->usesEH();
}

int S_PragmaStatement::blockExit()
{
    int result = BEfallthru;
#if 0 // currently, no code is generated for Pragma's, so it's just fallthru
    if (arrayExpressionCanThrow(args))
	result |= BEthrow;
    if (body)
	result |= body->blockExit();
#endif
    return result;
}


void S_PragmaStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("pragma (");
    buf->writestring(ident->oToChars());
    if (args && args->dim)
    {
	buf->writestring(", ");
	argsToCBuffer(buf, args, hgs);
    }
    buf->writeByte(')');
    if (body)
    {
	buf->writenl();
	buf->writeByte('{');
	buf->writenl();

	body->toCBuffer(buf, hgs);

	buf->writeByte('}');
	buf->writenl();
    }
    else
    {
	buf->writeByte(';');
	buf->writenl();
    }
}


/******************************** S_StaticAssertStatement ***************************/

S_StaticAssertStatement::S_StaticAssertStatement(P_StaticAssert *sa)
    : S_Statement(sa->loc)
{
    this->sa = sa;
}

S_Statement *S_StaticAssertStatement::syntaxCopy()
{
    S_StaticAssertStatement *s = new S_StaticAssertStatement((P_StaticAssert *)sa->syntaxCopy(NULL));
    return s;
}

S_Statement *S_StaticAssertStatement::semantic(Scope *sc)
{
    sa->semantic2(sc);
    return NULL;
}

void S_StaticAssertStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    sa->toCBuffer(buf, hgs);
}


/******************************** S_SwitchStatement ***************************/

S_SwitchStatement::S_SwitchStatement(Loc loc, E_Expression *c, S_Statement *b)
    : S_Statement(loc)
{
    condition = c;
    body = b;
    sdefault = NULL;
    tf = NULL;
    cases = NULL;
    hasNoDefault = 0;
    hasVars = 0;
}

S_Statement *S_SwitchStatement::syntaxCopy()
{
    S_SwitchStatement *s = new S_SwitchStatement(loc,
	condition->syntaxCopy(), body->syntaxCopy());
    return s;
}

S_Statement *S_SwitchStatement::semantic(Scope *sc)
{
    //printf("S_SwitchStatement::semantic(%p)\n", this);
    tf = sc->tf;
    assert(!cases);		// ensure semantic() is only run once
    condition = condition->semantic(sc);
    condition = resolveProperties(sc, condition);
    if (condition->type->isString())
    {
	// If it's not an array, cast it to one
	if (condition->type->ty != Tarray)
	{
	    condition = condition->implicitCastTo(sc, condition->type->nextOf()->arrayOf());
	}
	condition->type = condition->type->constOf();
    }
    else
    {	condition = condition->integralPromotions(sc);
	condition->checkIntegral();
    }
    condition = condition->optimize(WANTvalue);

    sc = sc->push();
    sc->sbreak = this;
    sc->sw = this;

    cases = new Array();
    sc->noctor++;	// BUG: should use Scope::mergeCallSuper() for each case instead
    body = body->semantic(sc);
    sc->noctor--;

    // Resolve any goto case's with exp
    for (int i = 0; i < gotoCases.dim; i++)
    {
	S_GotoCaseStatement *gcs = (S_GotoCaseStatement *)gotoCases.data[i];

	if (!gcs->exp)
	{
	    gcs->error("no case statement following goto case;");
	    break;
	}

	for (Scope *scx = sc; scx; scx = scx->enclosing)
	{
	    if (!scx->sw)
		continue;
	    for (int j = 0; j < scx->sw->cases->dim; j++)
	    {
		S_CaseStatement *cs = (S_CaseStatement *)scx->sw->cases->data[j];

		if (cs->exp->oEquals(gcs->exp))
		{
		    gcs->cs = cs;
		    goto Lfoundcase;
		}
	    }
	}
	gcs->error("case %s not found", gcs->exp->oToChars());

     Lfoundcase:
	;
    }

    if (!sc->sw->sdefault)
    {	hasNoDefault = 1;

	warning("switch statement has no default");

	// Generate runtime error if the default is hit
	Statements *a = new Statements();
	S_CompoundStatement *cs;
	S_Statement *s;

	if (global.params.useSwitchError)
	    s = new S_SwitchErrorStatement(loc);
	else
	{   E_Expression *e = new E_HaltExp(loc);
	    s = new S_ExpStatement(loc, e);
	}

	a->reserve(4);
	a->push(body);
	a->push(new S_BreakStatement(loc, NULL));
	sc->sw->sdefault = new S_DefaultStatement(loc, s);
	a->push(sc->sw->sdefault);
	cs = new S_CompoundStatement(loc, a);
	body = cs;
    }

    sc->pop();
    return this;
}

int S_SwitchStatement::hasBreak()
{
    return TRUE;
}

int S_SwitchStatement::usesEH()
{
    return body ? body->usesEH() : 0;
}

int S_SwitchStatement::blockExit()
{   int result = BEnone;
    if (condition->canThrow())
	result |= BEthrow;

    if (body)
    {	result |= body->blockExit();
	if (result & BEbreak)
	{   result |= BEfallthru;
	    result &= ~BEbreak;
	}
    }
    else
	result |= BEfallthru;

    return result;
}


void S_SwitchStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("switch (");
    condition->toCBuffer(buf, hgs);
    buf->writebyte(')');
    buf->writenl();
    if (body)
    {
	if (!body->isScopeStatement())
        {   buf->writebyte('{');
            buf->writenl();
            body->toCBuffer(buf, hgs);
            buf->writebyte('}');
            buf->writenl();
        }
        else
        {
            body->toCBuffer(buf, hgs);
        }
    }
}

/******************************** S_CaseStatement ***************************/

S_CaseStatement::S_CaseStatement(Loc loc, E_Expression *exp, S_Statement *s)
    : S_Statement(loc)
{
    this->exp = exp;
    this->statement = s;
    index = 0;
    cblock = NULL;
}

S_Statement *S_CaseStatement::syntaxCopy()
{
    S_CaseStatement *s = new S_CaseStatement(loc, exp->syntaxCopy(), statement->syntaxCopy());
    return s;
}

S_Statement *S_CaseStatement::semantic(Scope *sc)
{   S_SwitchStatement *sw = sc->sw;

    //printf("S_CaseStatement::semantic() %s\n", oToChars());
    exp = exp->semantic(sc);
    if (sw)
    {
	exp = exp->implicitCastTo(sc, sw->condition->type);
	exp = exp->optimize(WANTvalue | WANTinterpret);

	/* This is where variables are allowed as case expressions.
	 */
	if (exp->op == LT::TOKvar)
	{   E_VarExp *ve = (E_VarExp *)exp;
	    P_VarDeclaration *v = ve->var->isVarDeclaration();
	    Type *t = exp->type->toBasetype();
	    if (v && (t->isintegral() || t->ty == Tclass))
	    {	/* Flag that we need to do special code generation
		 * for this, i.e. generate a sequence of if-then-else
		 */
		sw->hasVars = 1;
		goto L1;
	    }
	}

	if (exp->op != LT::TOKstring && exp->op != LT::TOKint64)
	{
	    error("case must be a string or an integral constant, not %s", exp->oToChars());
	    exp = new E_IntegerExp(0);
	}

    L1:
	for (int i = 0; i < sw->cases->dim; i++)
	{
	    S_CaseStatement *cs = (S_CaseStatement *)sw->cases->data[i];

	    //printf("comparing '%s' with '%s'\n", exp->oToChars(), cs->exp->oToChars());
	    if (cs->exp->oEquals(exp))
	    {	error("duplicate case %s in switch statement", exp->oToChars());
		break;
	    }
	}

	sw->cases->push(this);

	// Resolve any goto case's with no exp to this case statement
	for (int i = 0; i < sw->gotoCases.dim; i++)
	{
	    S_GotoCaseStatement *gcs = (S_GotoCaseStatement *)sw->gotoCases.data[i];

	    if (!gcs->exp)
	    {
		gcs->cs = this;
		sw->gotoCases.remove(i);	// remove from array
	    }
	}

	if (sc->sw->tf != sc->tf)
	    error("switch and case are in different finally blocks");
    }
    else
	error("case not in switch statement");
    statement = statement->semantic(sc);
    return this;
}

int S_CaseStatement::oCompare(Object *obj)
{
    // Sort cases so we can do an efficient lookup
    S_CaseStatement *cs2 = (S_CaseStatement *)(obj);

    return exp->oCompare(cs2->exp);
}

int S_CaseStatement::usesEH()
{
    return statement->usesEH();
}

int S_CaseStatement::blockExit()
{
    return statement->blockExit();
}


int S_CaseStatement::comeFrom()
{
    return TRUE;
}

void S_CaseStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("case ");
    exp->toCBuffer(buf, hgs);
    buf->writebyte(':');
    buf->writenl();
    statement->toCBuffer(buf, hgs);
}

/******************************** S_DefaultStatement ***************************/

S_DefaultStatement::S_DefaultStatement(Loc loc, S_Statement *s)
    : S_Statement(loc)
{
    this->statement = s;
#if IN_GCC
+    cblock = NULL;
#endif
}

S_Statement *S_DefaultStatement::syntaxCopy()
{
    S_DefaultStatement *s = new S_DefaultStatement(loc, statement->syntaxCopy());
    return s;
}

S_Statement *S_DefaultStatement::semantic(Scope *sc)
{
    //printf("S_DefaultStatement::semantic()\n");
    if (sc->sw)
    {
	if (sc->sw->sdefault)
	{
	    error("switch statement already has a default");
	}
	sc->sw->sdefault = this;

	if (sc->sw->tf != sc->tf)
	    error("switch and default are in different finally blocks");
    }
    else
	error("default not in switch statement");
    statement = statement->semantic(sc);
    return this;
}

int S_DefaultStatement::usesEH()
{
    return statement->usesEH();
}

int S_DefaultStatement::blockExit()
{
    return statement->blockExit();
}


int S_DefaultStatement::comeFrom()
{
    return TRUE;
}

void S_DefaultStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("default:\n");
    statement->toCBuffer(buf, hgs);
}

/******************************** S_GotoDefaultStatement ***************************/

S_GotoDefaultStatement::S_GotoDefaultStatement(Loc loc)
    : S_Statement(loc)
{
    sw = NULL;
}

S_Statement *S_GotoDefaultStatement::syntaxCopy()
{
    S_GotoDefaultStatement *s = new S_GotoDefaultStatement(loc);
    return s;
}

S_Statement *S_GotoDefaultStatement::semantic(Scope *sc)
{
    sw = sc->sw;
    if (!sw)
	error("goto default not in switch statement");
    return this;
}

int S_GotoDefaultStatement::blockExit()
{
    return BEgoto;
}


void S_GotoDefaultStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("goto default;\n");
}

/******************************** S_GotoCaseStatement ***************************/

S_GotoCaseStatement::S_GotoCaseStatement(Loc loc, E_Expression *exp)
    : S_Statement(loc)
{
    cs = NULL;
    this->exp = exp;
}

S_Statement *S_GotoCaseStatement::syntaxCopy()
{
    E_Expression *e = exp ? exp->syntaxCopy() : NULL;
    S_GotoCaseStatement *s = new S_GotoCaseStatement(loc, e);
    return s;
}

S_Statement *S_GotoCaseStatement::semantic(Scope *sc)
{
    if (exp)
	exp = exp->semantic(sc);

    if (!sc->sw)
	error("goto case not in switch statement");
    else
    {
	sc->sw->gotoCases.push(this);
	if (exp)
	{
	    exp = exp->implicitCastTo(sc, sc->sw->condition->type);
	    exp = exp->optimize(WANTvalue);
	}
    }
    return this;
}

int S_GotoCaseStatement::blockExit()
{
    return BEgoto;
}


void S_GotoCaseStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("goto case");
    if (exp)
    {   buf->writebyte(' ');
        exp->toCBuffer(buf, hgs);
    }
    buf->writebyte(';');
    buf->writenl();
}

/******************************** S_SwitchErrorStatement ***************************/

S_SwitchErrorStatement::S_SwitchErrorStatement(Loc loc)
    : S_Statement(loc)
{
}

int S_SwitchErrorStatement::blockExit()
{
    return BEthrow;
}


void S_SwitchErrorStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("S_SwitchErrorStatement::toCBuffer()");
    buf->writenl();
}

/******************************** S_ReturnStatement ***************************/

S_ReturnStatement::S_ReturnStatement(Loc loc, E_Expression *exp)
    : S_Statement(loc)
{
    this->exp = exp;
}

S_Statement *S_ReturnStatement::syntaxCopy()
{
    E_Expression *e = NULL;
    if (exp)
	e = exp->syntaxCopy();
    S_ReturnStatement *s = new S_ReturnStatement(loc, e);
    return s;
}

S_Statement *S_ReturnStatement::semantic(Scope *sc)
{
    //printf("S_ReturnStatement::semantic() %s\n", oToChars());

    P_FuncDeclaration *fd = sc->parent->isFuncDeclaration();
    Scope *scx = sc;
    int implicit0 = 0;

    if (sc->fes)
    {
	// Find scope of function foreach is in
	for (; 1; scx = scx->enclosing)
	{
	    assert(scx);
	    if (scx->func != fd)
	    {	fd = scx->func;		// fd is now function enclosing foreach
		break;
	    }
	}
    }

    Type *tret = fd->type->nextOf();
    if (fd->tintro)
	/* We'll be implicitly casting the return expression to tintro
	 */
	tret = fd->tintro->nextOf();
    Type *tbret = NULL;

    if (tret)
	tbret = tret->toBasetype();

    // main() returns 0, even if it returns void
    if (!exp && (!tbret || tbret->ty == Tvoid) && fd->isMain())
    {	implicit0 = 1;
	exp = new E_IntegerExp(0);
    }

    if (sc->incontract || scx->incontract)
	error("return statements cannot be in contracts");
    if (sc->tf || scx->tf)
	error("return statements cannot be in finally, scope(exit) or scope(success) bodies");

    if (fd->isCtorDeclaration())
    {
	// Constructors implicitly do:
	//	return this;
	if (exp && exp->op != LT::TOKthis)
	    error("cannot return expression from constructor");
	exp = new E_ThisExp(0);
    }

    if (!exp)
	fd->nrvo_can = 0;

    if (exp)
    {
	fd->hasReturnExp |= 1;

	exp = exp->semantic(sc);
	exp = resolveProperties(sc, exp);
	exp = exp->optimize(WANTvalue);

	if (fd->nrvo_can && exp->op == LT::TOKvar)
	{   E_VarExp *ve = (E_VarExp *)exp;
	    P_VarDeclaration *v = ve->var->isVarDeclaration();

	    if (((TypeFunction *)fd->type)->isref)
		// Function returns a reference
		fd->nrvo_can = 0;
	    else if (!v || v->isOut() || v->isRef())
		fd->nrvo_can = 0;
	    else if (tbret->ty == Tstruct && ((TypeStruct *)tbret)->sym->dtor)
		// Struct being returned has destructors
		fd->nrvo_can = 0;
	    else if (fd->nrvo_var == NULL)
	    {	if (!v->isDataseg() && !v->isParameter() && v->toParent2() == fd)
		{   //printf("Setting nrvo to %s\n", v->oToChars());
		    fd->nrvo_var = v;
		}
		else
		    fd->nrvo_can = 0;
	    }
	    else if (fd->nrvo_var != v)
		fd->nrvo_can = 0;
	}
	else
	    fd->nrvo_can = 0;

	if (fd->returnLabel && tbret->ty != Tvoid)
	{
	}
	else if (fd->inferRetType)
	{
	    if (fd->type->nextOf())
	    {
		if (!exp->type->oEquals(fd->type->nextOf()))
		    error("mismatched function return type inference of %s and %s",
			exp->type->oToChars(), fd->type->nextOf()->oToChars());
	    }
	    else
	    {
		((TypeFunction *)fd->type)->next = exp->type;
		fd->type = fd->type->semantic(loc, sc);
		if (!fd->tintro)
		{   tret = fd->type->nextOf();
		    tbret = tret->toBasetype();
		}
	    }
	}
	else if (tbret->ty != Tvoid)
	{
	    exp = exp->implicitCastTo(sc, tret);
	}
    }
    else if (fd->inferRetType)
    {
	if (fd->type->nextOf())
	{
	    if (fd->type->nextOf()->ty != Tvoid)
		error("mismatched function return type inference of void and %s",
		    fd->type->nextOf()->oToChars());
	}
	else
	{
	    ((TypeFunction *)fd->type)->next = Type::tvoid;
	    fd->type = fd->type->semantic(loc, sc);
	    if (!fd->tintro)
	    {   tret = Type::tvoid;
		tbret = tret;
	    }
	}
    }
    else if (tbret->ty != Tvoid)	// if non-void return
	error("return expression expected");

    if (sc->fes)
    {
	S_Statement *s;

	if (exp && !implicit0)
	{
	    exp = exp->implicitCastTo(sc, tret);
	}
	if (!exp || exp->op == LT::TOKint64 || exp->op == LT::TOKfloat64 ||
	    exp->op == LT::TOKimaginary80 || exp->op == LT::TOKcomplex80 ||
	    exp->op == LT::TOKthis || exp->op == LT::TOKsuper || exp->op == LT::TOKnull ||
	    exp->op == LT::TOKstring)
	{
	    sc->fes->cases.push(this);
	    // Construct: return cases.dim+1;
	    s = new S_ReturnStatement(0, new E_IntegerExp(sc->fes->cases.dim + 1));
	}
	else if (fd->type->nextOf()->toBasetype() == Type::tvoid)
	{
	    s = new S_ReturnStatement(0, NULL);
	    sc->fes->cases.push(s);

	    // Construct: { exp; return cases.dim + 1; }
	    S_Statement *s1 = new S_ExpStatement(loc, exp);
	    S_Statement *s2 = new S_ReturnStatement(0, new E_IntegerExp(sc->fes->cases.dim + 1));
	    s = new S_CompoundStatement(loc, s1, s2);
	}
	else
	{
	    // Construct: return vresult;
	    if (!fd->vresult)
	    {	// Declare vresult
		P_VarDeclaration *v = new P_VarDeclaration(loc, tret, Id::result, NULL);
		v->noauto = 1;
		v->semantic(scx);
		if (!scx->insert(v))
		    assert(0);
		v->parent = fd;
		fd->vresult = v;
	    }

	    s = new S_ReturnStatement(0, new E_VarExp(0, fd->vresult));
	    sc->fes->cases.push(s);

	    // Construct: { vresult = exp; return cases.dim + 1; }
	    exp = new E_AssignExp(loc, new E_VarExp(0, fd->vresult), exp);
	    exp = exp->semantic(sc);
	    S_Statement *s1 = new S_ExpStatement(loc, exp);
	    S_Statement *s2 = new S_ReturnStatement(0, new E_IntegerExp(sc->fes->cases.dim + 1));
	    s = new S_CompoundStatement(loc, s1, s2);
	}
	return s;
    }

    if (exp)
    {
	if (fd->returnLabel && tbret->ty != Tvoid)
	{
	    assert(fd->vresult);
	    E_VarExp *v = new E_VarExp(0, fd->vresult);

	    exp = new E_AssignExp(loc, v, exp);
	    exp = exp->semantic(sc);
	}

	if (((TypeFunction *)fd->type)->isref && !fd->isCtorDeclaration())
	{   // Function returns a reference
	    if (tbret->isMutable())
		exp = exp->modifiableLvalue(sc, exp);
	    else
		exp = exp->toLvalue(sc, exp);

	    if (exp->op == LT::TOKvar)
	    {	E_VarExp *ve = (E_VarExp *)exp;
		P_VarDeclaration *v = ve->var->isVarDeclaration();
		if (v && !v->isDataseg() && !(v->storage_class & (STCref | STCout)))
		    error("escaping reference to local variable %s", v->oToChars());
	    }
	}

	//exp->dump(0);
	//exp->oPrint();
	exp->checkEscape();
    }

    /* BUG: need to issue an error on:
     *	this
     *	{   if (x) return;
     *	    super();
     *	}
     */

    if (sc->callSuper & CSXany_ctor &&
	!(sc->callSuper & (CSXthis_ctor | CSXsuper_ctor)))
	error("return without calling constructor");

    sc->callSuper |= CSXreturn;

    // See if all returns are instead to be replaced with a goto returnLabel;
    if (fd->returnLabel)
    {
	S_GotoStatement *gs = new S_GotoStatement(loc, Id::returnLabel);

	gs->label = fd->returnLabel;
	if (exp)
	{   /* Replace: return exp;
	     * with:    exp; goto returnLabel;
	     */
	    S_Statement *s = new S_ExpStatement(0, exp);
	    return new S_CompoundStatement(loc, s, gs);
	}
	return gs;
    }

    if (exp && tbret->ty == Tvoid && !fd->isMain())
    {
	/* Replace:
	 *	return exp;
	 * with:
	 *	exp; return;
	 */
	S_Statement *s = new S_ExpStatement(loc, exp);
	loc = 0;
	exp = NULL;
	return new S_CompoundStatement(loc, s, this);
    }

    return this;
}

int S_ReturnStatement::blockExit()
{   int result = BEreturn;

    if (exp && exp->canThrow())
	result |= BEthrow;
    return result;
}


void S_ReturnStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->printf("return ");
    if (exp)
	exp->toCBuffer(buf, hgs);
    buf->writeByte(';');
    buf->writenl();
}

/******************************** S_BreakStatement ***************************/

S_BreakStatement::S_BreakStatement(Loc loc, Identifier *ident)
    : S_Statement(loc)
{
    this->ident = ident;
}

S_Statement *S_BreakStatement::syntaxCopy()
{
    S_BreakStatement *s = new S_BreakStatement(loc, ident);
    return s;
}

S_Statement *S_BreakStatement::semantic(Scope *sc)
{
    //printf("S_BreakStatement::semantic()\n");
    // If:
    //	break Identifier;
    if (ident)
    {
	Scope *scx;
	P_FuncDeclaration *thisfunc = sc->func;

	for (scx = sc; scx; scx = scx->enclosing)
	{
	    S_LabelStatement *ls;

	    if (scx->func != thisfunc)	// if in enclosing function
	    {
		if (sc->fes)		// if this is the body of a foreach
		{
		    /* Post this statement to the fes, and replace
		     * it with a return value that caller will put into
		     * a switch. Caller will figure out where the break
		     * label actually is.
		     * Case numbers start with 2, not 0, as 0 is continue
		     * and 1 is break.
		     */
		    S_Statement *s;
		    sc->fes->cases.push(this);
		    s = new S_ReturnStatement(0, new E_IntegerExp(sc->fes->cases.dim + 1));
		    return s;
		}
		break;			// can't break to it
	    }

	    ls = scx->slabel;
	    if (ls && ls->ident == ident)
	    {
		S_Statement *s = ls->statement;

		if (!s->hasBreak())
		    error("label '%s' has no break", ident->oToChars());
		if (ls->tf != sc->tf)
		    error("cannot break out of finally block");
		return this;
	    }
	}
	error("enclosing label '%s' for break not found", ident->oToChars());
    }
    else if (!sc->sbreak)
    {
	if (sc->fes)
	{   S_Statement *s;

	    // Replace break; with return 1;
	    s = new S_ReturnStatement(0, new E_IntegerExp(1));
	    return s;
	}
	error("break is not inside a loop or switch");
    }
    return this;
}

int S_BreakStatement::blockExit()
{
    //printf("S_BreakStatement::blockExit(%p) = x%x\n", this, ident ? BEgoto : BEbreak);
    return ident ? BEgoto : BEbreak;
}


void S_BreakStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("break");
    if (ident)
    {   buf->writebyte(' ');
        buf->writestring(ident->oToChars());
    }
    buf->writebyte(';');
    buf->writenl();
}

/******************************** S_ContinueStatement ***************************/

S_ContinueStatement::S_ContinueStatement(Loc loc, Identifier *ident)
    : S_Statement(loc)
{
    this->ident = ident;
}

S_Statement *S_ContinueStatement::syntaxCopy()
{
    S_ContinueStatement *s = new S_ContinueStatement(loc, ident);
    return s;
}

S_Statement *S_ContinueStatement::semantic(Scope *sc)
{
    //printf("S_ContinueStatement::semantic() %p\n", this);
    if (ident)
    {
	Scope *scx;
	P_FuncDeclaration *thisfunc = sc->func;

	for (scx = sc; scx; scx = scx->enclosing)
	{
	    S_LabelStatement *ls;

	    if (scx->func != thisfunc)	// if in enclosing function
	    {
		if (sc->fes)		// if this is the body of a foreach
		{
		    for (; scx; scx = scx->enclosing)
		    {
			ls = scx->slabel;
			if (ls && ls->ident == ident && ls->statement == sc->fes)
			{
			    // Replace continue ident; with return 0;
			    return new S_ReturnStatement(0, new E_IntegerExp(0));
			}
		    }

		    /* Post this statement to the fes, and replace
		     * it with a return value that caller will put into
		     * a switch. Caller will figure out where the break
		     * label actually is.
		     * Case numbers start with 2, not 0, as 0 is continue
		     * and 1 is break.
		     */
		    S_Statement *s;
		    sc->fes->cases.push(this);
		    s = new S_ReturnStatement(0, new E_IntegerExp(sc->fes->cases.dim + 1));
		    return s;
		}
		break;			// can't continue to it
	    }

	    ls = scx->slabel;
	    if (ls && ls->ident == ident)
	    {
		S_Statement *s = ls->statement;

		if (!s->hasContinue())
		    error("label '%s' has no continue", ident->oToChars());
		if (ls->tf != sc->tf)
		    error("cannot continue out of finally block");
		return this;
	    }
	}
	error("enclosing label '%s' for continue not found", ident->oToChars());
    }
    else if (!sc->scontinue)
    {
	if (sc->fes)
	{   S_Statement *s;

	    // Replace continue; with return 0;
	    s = new S_ReturnStatement(0, new E_IntegerExp(0));
	    return s;
	}
	error("continue is not inside a loop");
    }
    return this;
}

int S_ContinueStatement::blockExit()
{
    return ident ? BEgoto : BEcontinue;
}


void S_ContinueStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("continue");
    if (ident)
    {   buf->writebyte(' ');
        buf->writestring(ident->oToChars());
    }
    buf->writebyte(';');
    buf->writenl();
}

/******************************** S_SynchronizedStatement ***************************/

S_SynchronizedStatement::S_SynchronizedStatement(Loc loc, E_Expression *exp, S_Statement *body)
    : S_Statement(loc)
{
    this->exp = exp;
    this->body = body;
    this->esync = NULL;
}

S_SynchronizedStatement::S_SynchronizedStatement(Loc loc, elem *esync, S_Statement *body)
    : S_Statement(loc)
{
    this->exp = NULL;
    this->body = body;
    this->esync = esync;
}

S_Statement *S_SynchronizedStatement::syntaxCopy()
{
    E_Expression *e = exp ? exp->syntaxCopy() : NULL;
    S_SynchronizedStatement *s = new S_SynchronizedStatement(loc, e, body ? body->syntaxCopy() : NULL);
    return s;
}

S_Statement *S_SynchronizedStatement::semantic(Scope *sc)
{
    if (exp)
    {	P_ClassDeclaration *cd;

	exp = exp->semantic(sc);
	exp = resolveProperties(sc, exp);
	cd = exp->type->isClassHandle();
	if (!cd)
	    error("can only synchronize on class objects, not '%s'", exp->type->oToChars());
	else if (cd->isInterfaceDeclaration())
	{   Type *t = new TypeIdentifier(0, Id::Object);

	    t = t->semantic(0, sc);
	    exp = new E_CastExp(loc, exp, t);
	    exp = exp->semantic(sc);
	}
    }
    if (body)
	body = body->semantic(sc);
    return this;
}

int S_SynchronizedStatement::hasBreak()
{
    return FALSE; //TRUE;
}

int S_SynchronizedStatement::hasContinue()
{
    return FALSE; //TRUE;
}

int S_SynchronizedStatement::usesEH()
{
    return TRUE;
}

int S_SynchronizedStatement::blockExit()
{
    return body ? body->blockExit() : BEfallthru;
}


void S_SynchronizedStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("synchronized");
    if (exp)
    {   buf->writebyte('(');
	exp->toCBuffer(buf, hgs);
	buf->writebyte(')');
    }
    if (body)
    {
	buf->writebyte(' ');
	body->toCBuffer(buf, hgs);
    }
}

/******************************** S_WithStatement ***************************/

S_WithStatement::S_WithStatement(Loc loc, E_Expression *exp, S_Statement *body)
    : S_Statement(loc)
{
    this->exp = exp;
    this->body = body;
    wthis = NULL;
}

S_Statement *S_WithStatement::syntaxCopy()
{
    S_WithStatement *s = new S_WithStatement(loc, exp->syntaxCopy(), body ? body->syntaxCopy() : NULL);
    return s;
}

S_Statement *S_WithStatement::semantic(Scope *sc)
{   P_ScopeDsymbol *sym;
    Initializer *init;

    //printf("S_WithStatement::semantic()\n");
    exp = exp->semantic(sc);
    exp = resolveProperties(sc, exp);
    if (exp->op == LT::TOKimport)
    {	E_ScopeExp *es = (E_ScopeExp *)exp;

	sym = es->sds;
    }
    else if (exp->op == LT::TOKtype)
    {	E_TypeExp *es = (E_TypeExp *)exp;

	sym = es->type->toDsymbol(sc)->isScopeDsymbol();
	if (!sym)
	{   error("%s has no members", es->oToChars());
	    body = body->semantic(sc);
	    return this;
	}
    }
    else
    {	Type *t = exp->type;

	assert(t);
	t = t->toBasetype();
	if (t->isClassHandle())
	{
	    init = new ExpInitializer(loc, exp);
	    wthis = new P_VarDeclaration(loc, exp->type, Id::withSym, init);
	    wthis->semantic(sc);

	    sym = new P_WithScopeSymbol(this);
	    sym->parent = sc->scopesym;
	}
	else if (t->ty == Tstruct)
	{
	    E_Expression *e = exp->addressOf(sc);
	    init = new ExpInitializer(loc, e);
	    wthis = new P_VarDeclaration(loc, e->type, Id::withSym, init);
	    wthis->semantic(sc);
	    sym = new P_WithScopeSymbol(this);
	    sym->parent = sc->scopesym;
	}
	else
	{   error("with expressions must be class objects, not '%s'", exp->type->oToChars());
	    return NULL;
	}
    }
    sc = sc->push(sym);

    if (body)
	body = body->semantic(sc);

    sc->pop();

    return this;
}

void S_WithStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("with (");
    exp->toCBuffer(buf, hgs);
    buf->writestring(")\n");
    if (body)
	body->toCBuffer(buf, hgs);
}

int S_WithStatement::usesEH()
{
    return body ? body->usesEH() : 0;
}

int S_WithStatement::blockExit()
{
    int result = BEnone;
    if (exp->canThrow())
	result = BEthrow;
    if (body)
	result |= body->blockExit();
    else
	result |= BEfallthru;
    return result;
}


/******************************** S_TryCatchStatement ***************************/

S_TryCatchStatement::S_TryCatchStatement(Loc loc, S_Statement *body, Array *catches)
    : S_Statement(loc)
{
    this->body = body;
    this->catches = catches;
}

S_Statement *S_TryCatchStatement::syntaxCopy()
{
    Array *a = new Array();
    a->setDim(catches->dim);
    for (int i = 0; i < a->dim; i++)
    {   Catch *c;

	c = (Catch *)catches->data[i];
	c = c->syntaxCopy();
	a->data[i] = c;
    }
    S_TryCatchStatement *s = new S_TryCatchStatement(loc, body->syntaxCopy(), a);
    return s;
}

S_Statement *S_TryCatchStatement::semantic(Scope *sc)
{
    body = body->semanticScope(sc, NULL /*this*/, NULL);

    /* Even if body is NULL, still do semantic analysis on catches
     */
    for (size_t i = 0; i < catches->dim; i++)
    {   Catch *c = (Catch *)catches->data[i];
	c->semantic(sc);

	// Determine if current catch 'hides' any previous catches
	for (size_t j = 0; j < i; j++)
	{   Catch *cj = (Catch *)catches->data[j];
	    char *si = c->loc.toChars();
	    char *sj = cj->loc.toChars();

	    if (c->type->toBasetype()->implicitConvTo(cj->type->toBasetype()))
		error("catch at %s hides catch at %s", sj, si);
	}
    }

    if (!body)
	return NULL;

    return this;
}

int S_TryCatchStatement::hasBreak()
{
    return FALSE; //TRUE;
}

int S_TryCatchStatement::usesEH()
{
    return TRUE;
}

int S_TryCatchStatement::blockExit()
{
    assert(body);
    int result = body->blockExit();

    int catchresult = 0;
    for (size_t i = 0; i < catches->dim; i++)
    {
        Catch *c = (Catch *)catches->data[i];
        catchresult |= c->blockExit();

	/* If we're catching Object, then there is no throwing
	 */
	Identifier *id = c->type->toBasetype()->isClassHandle()->ident;
	if (i == 0 &&
	    (id == Id::Object || id == Id::Throwable || id == Id::Exception))
	{
	    result &= ~BEthrow;
	}
    }
    return result | catchresult;
}


void S_TryCatchStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("try");
    buf->writenl();
    if (body)
        body->toCBuffer(buf, hgs);
    for (size_t i = 0; i < catches->dim; i++)
    {
        Catch *c = (Catch *)catches->data[i];
        c->toCBuffer(buf, hgs);
    }
}

/******************************** Catch ***************************/

Catch::Catch(Loc loc, Type *t, Identifier *id, S_Statement *handler)
{
    //printf("Catch(%s, loc = %s)\n", id->oToChars(), loc.oToChars());
    this->loc = loc;
    this->type = t;
    this->ident = id;
    this->handler = handler;
    var = NULL;
}

Catch *Catch::syntaxCopy()
{
    Catch *c = new Catch(loc,
	(type ? type->syntaxCopy() : NULL),
	ident,
	(handler ? handler->syntaxCopy() : NULL));
    return c;
}

void Catch::semantic(Scope *sc)
{   P_ScopeDsymbol *sym;

    //printf("Catch::semantic(%s)\n", ident->oToChars());

#ifndef IN_GCC
    if (sc->tf)
    {
	/* This is because the _d_local_unwind() gets the stack munged
	 * up on this. The workaround is to place any try-catches into
	 * a separate function, and call that.
	 * To fix, have the compiler automatically convert the finally
	 * body into a nested function.
	 */
	error(loc, "cannot put catch statement inside finally block");
    }
#endif

    sym = new P_ScopeDsymbol();
    sym->parent = sc->scopesym;
    sc = sc->push(sym);

    if (!type)
	type = new TypeIdentifier(0, Id::Object);
    type = type->semantic(loc, sc);
    if (!type->toBasetype()->isClassHandle())
	error("can only catch class objects, not '%s'", type->oToChars());
    else if (ident)
    {
	var = new P_VarDeclaration(loc, type, ident, NULL);
	var->parent = sc->parent;
	sc->insert(var);
    }
    handler = handler->semantic(sc);

    sc->pop();
}

int Catch::blockExit()
{
    return handler ? handler->blockExit() : BEfallthru;
}

void Catch::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("catch");
    if (type)
    {   buf->writebyte('(');
	type->toCBuffer(buf, ident, hgs);
        buf->writebyte(')');
    }
    buf->writenl();
    buf->writebyte('{');
    buf->writenl();
    if (handler)
	handler->toCBuffer(buf, hgs);
    buf->writebyte('}');
    buf->writenl();
}

/****************************** S_TryFinallyStatement ***************************/

S_TryFinallyStatement::S_TryFinallyStatement(Loc loc, S_Statement *body, S_Statement *finalbody)
    : S_Statement(loc)
{
    this->body = body;
    this->finalbody = finalbody;
}

S_Statement *S_TryFinallyStatement::syntaxCopy()
{
    S_TryFinallyStatement *s = new S_TryFinallyStatement(loc,
	body->syntaxCopy(), finalbody->syntaxCopy());
    return s;
}

S_Statement *S_TryFinallyStatement::semantic(Scope *sc)
{
    //printf("S_TryFinallyStatement::semantic()\n");
    body = body->semantic(sc);
    sc = sc->push();
    sc->tf = this;
    sc->sbreak = NULL;
    sc->scontinue = NULL;	// no break or continue out of finally block
    finalbody = finalbody->semantic(sc);
    sc->pop();
    if (!body)
	return finalbody;
    if (!finalbody)
	return body;
    if (body->blockExit() == BEfallthru)
    {	S_Statement *s = new S_CompoundStatement(loc, body, finalbody);
	return s;
    }
    return this;
}

void S_TryFinallyStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->printf("try\n{\n");
    body->toCBuffer(buf, hgs);
    buf->printf("}\nfinally\n{\n");
    finalbody->toCBuffer(buf, hgs);
    buf->writeByte('}');
    buf->writenl();
}

int S_TryFinallyStatement::hasBreak()
{
    return FALSE; //TRUE;
}

int S_TryFinallyStatement::hasContinue()
{
    return FALSE; //TRUE;
}

int S_TryFinallyStatement::usesEH()
{
    return TRUE;
}

int S_TryFinallyStatement::blockExit()
{
    if (body)
	return body->blockExit();
    return BEfallthru;
}


/****************************** S_OnScopeStatement ***************************/

S_OnScopeStatement::S_OnScopeStatement(Loc loc, LT::T tok, S_Statement *statement)
    : S_Statement(loc)
{
    this->tok = tok;
    this->statement = statement;
}

S_Statement *S_OnScopeStatement::syntaxCopy()
{
    S_OnScopeStatement *s = new S_OnScopeStatement(loc,
	tok, statement->syntaxCopy());
    return s;
}

S_Statement *S_OnScopeStatement::semantic(Scope *sc)
{
    /* semantic is called on results of scopeCode() */
    return this;
}

int S_OnScopeStatement::blockExit()
{   // At this point, this statement is just an empty placeholder
    return BEfallthru;
}

void S_OnScopeStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring(Token::toChars(tok));
    buf->writebyte(' ');
    statement->toCBuffer(buf, hgs);
}

int S_OnScopeStatement::usesEH()
{
    return 1;
}

void S_OnScopeStatement::scopeCode(Scope *sc, S_Statement **sentry, S_Statement **sexception, S_Statement **sfinally)
{
    //printf("S_OnScopeStatement::scopeCode()\n");
    //oPrint();
    *sentry = NULL;
    *sexception = NULL;
    *sfinally = NULL;
    switch (tok)
    {
	case LT::TOKon_scope_exit:
	    *sfinally = statement;
	    break;

	case LT::TOKon_scope_failure:
	    *sexception = statement;
	    break;

	case LT::TOKon_scope_success:
	{
	    /* Create:
	     *	sentry:   int x = 0;
	     *	sexception:    x = 1;
	     *	sfinally: if (!x) statement;
	     */
	    Identifier *id = Lexer::uniqueId("__os");

	    ExpInitializer *ie = new ExpInitializer(loc, new E_IntegerExp(0));
	    P_VarDeclaration *v = new P_VarDeclaration(loc, Type::tint32, id, ie);
	    *sentry = new S_DeclarationStatement(loc, v);

	    E_Expression *e = new E_IntegerExp(1);
	    e = new E_AssignExp(0, new E_VarExp(0, v), e);
	    *sexception = new S_ExpStatement(0, e);

	    e = new E_VarExp(0, v);
	    e = new E_NotExp(0, e);
	    *sfinally = new S_IfStatement(0, NULL, e, statement, NULL);

	    break;
	}

	default:
	    assert(0);
    }
}

/******************************** S_ThrowStatement ***************************/

S_ThrowStatement::S_ThrowStatement(Loc loc, E_Expression *exp)
    : S_Statement(loc)
{
    this->exp = exp;
}

S_Statement *S_ThrowStatement::syntaxCopy()
{
    S_ThrowStatement *s = new S_ThrowStatement(loc, exp->syntaxCopy());
    return s;
}

S_Statement *S_ThrowStatement::semantic(Scope *sc)
{
    //printf("S_ThrowStatement::semantic()\n");

    P_FuncDeclaration *fd = sc->parent->isFuncDeclaration();
    fd->hasReturnExp |= 2;

    if (sc->incontract)
	error("Throw statements cannot be in contracts");
    exp = exp->semantic(sc);
    exp = resolveProperties(sc, exp);
    if (!exp->type->toBasetype()->isClassHandle())
	error("can only throw class objects, not type %s", exp->type->oToChars());
    return this;
}

int S_ThrowStatement::blockExit()
{
    return BEthrow;  // obviously
}


void S_ThrowStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->printf("throw ");
    exp->toCBuffer(buf, hgs);
    buf->writeByte(';');
    buf->writenl();
}

/******************************** S_VolatileStatement **************************/

S_VolatileStatement::S_VolatileStatement(Loc loc, S_Statement *statement)
    : S_Statement(loc)
{
    this->statement = statement;
}

S_Statement *S_VolatileStatement::syntaxCopy()
{
    S_VolatileStatement *s = new S_VolatileStatement(loc,
		statement ? statement->syntaxCopy() : NULL);
    return s;
}

S_Statement *S_VolatileStatement::semantic(Scope *sc)
{
    if (statement)
	statement = statement->semantic(sc);
    return this;
}

Statements *S_VolatileStatement::flatten(Scope *sc)
{
    Statements *a;

    a = statement ? statement->flatten(sc) : NULL;
    if (a)
    {	for (int i = 0; i < a->dim; i++)
	{   S_Statement *s = (S_Statement *)a->data[i];

	    s = new S_VolatileStatement(loc, s);
	    a->data[i] = s;
	}
    }

    return a;
}

int S_VolatileStatement::blockExit()
{
    return statement ? statement->blockExit() : BEfallthru;
}


void S_VolatileStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("volatile");
    if (statement)
    {   if (statement->isScopeStatement())
            buf->writenl();
        else
            buf->writebyte(' ');
        statement->toCBuffer(buf, hgs);
    }
}


/******************************** S_GotoStatement ***************************/

S_GotoStatement::S_GotoStatement(Loc loc, Identifier *ident)
    : S_Statement(loc)
{
    this->ident = ident;
    this->label = NULL;
    this->tf = NULL;
}

S_Statement *S_GotoStatement::syntaxCopy()
{
    S_GotoStatement *s = new S_GotoStatement(loc, ident);
    return s;
}

S_Statement *S_GotoStatement::semantic(Scope *sc)
{   P_FuncDeclaration *fd = sc->parent->isFuncDeclaration();

    //printf("S_GotoStatement::semantic()\n");
    tf = sc->tf;
    label = fd->searchLabel(ident);
    if (!label->statement && sc->fes)
    {
	/* Either the goto label is forward referenced or it
	 * is in the function that the enclosing foreach is in.
	 * Can't know yet, so wrap the goto in a compound statement
	 * so we can patch it later, and add it to a 'look at this later'
	 * list.
	 */
	Statements *a = new Statements();
	S_Statement *s;

	a->push(this);
	s = new S_CompoundStatement(loc, a);
	sc->fes->gotos.push(s);		// 'look at this later' list
	return s;
    }
    if (label->statement && label->statement->tf != sc->tf)
	error("cannot goto in or out of finally block");
    return this;
}

int S_GotoStatement::blockExit()
{
    //printf("S_GotoStatement::blockExit(%p)\n", this);
    return BEgoto;
}


void S_GotoStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("goto ");
    buf->writestring(ident->oToChars());
    buf->writebyte(';');
    buf->writenl();
}

/******************************** S_LabelStatement ***************************/

S_LabelStatement::S_LabelStatement(Loc loc, Identifier *ident, S_Statement *statement)
    : S_Statement(loc)
{
    this->ident = ident;
    this->statement = statement;
    this->tf = NULL;
    this->lblock = NULL;
    this->isReturnLabel = 0;
}

S_Statement *S_LabelStatement::syntaxCopy()
{
    S_LabelStatement *s = new S_LabelStatement(loc, ident, statement->syntaxCopy());
    return s;
}

S_Statement *S_LabelStatement::semantic(Scope *sc)
{   P_LabelDsymbol *ls;
    P_FuncDeclaration *fd = sc->parent->isFuncDeclaration();

    //printf("S_LabelStatement::semantic()\n");
    ls = fd->searchLabel(ident);
    if (ls->statement)
	error("Label '%s' already defined", ls->oToChars());
    else
	ls->statement = this;
    tf = sc->tf;
    sc = sc->push();
    sc->scopesym = sc->enclosing->scopesym;
    sc->callSuper |= CSXlabel;
    sc->slabel = this;
    if (statement)
	statement = statement->semantic(sc);
    sc->pop();
    return this;
}

Statements *S_LabelStatement::flatten(Scope *sc)
{
    Statements *a = NULL;

    if (statement)
    {
	a = statement->flatten(sc);
	if (a)
	{
	    if (!a->dim)
	    {
		a->push(new S_ExpStatement(loc, NULL));
	    }
	    S_Statement *s = (S_Statement *)a->data[0];

	    s = new S_LabelStatement(loc, ident, s);
	    a->data[0] = s;
	}
    }

    return a;
}


int S_LabelStatement::usesEH()
{
    return statement ? statement->usesEH() : FALSE;
}

int S_LabelStatement::blockExit()
{
    //printf("S_LabelStatement::blockExit(%p)\n", this);
    return statement ? statement->blockExit() : BEfallthru;
}


int S_LabelStatement::comeFrom()
{
    //printf("S_LabelStatement::comeFrom()\n");
    return TRUE;
}

void S_LabelStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring(ident->oToChars());
    buf->writebyte(':');
    buf->writenl();
    if (statement)
        statement->toCBuffer(buf, hgs);
}


/******************************** P_LabelDsymbol ***************************/

P_LabelDsymbol::P_LabelDsymbol(Identifier *ident)
	: P_Dsymbol(ident)
{
    statement = NULL;
#if IN_GCC
    asmLabelNum = 0;
#endif
}

P_LabelDsymbol *P_LabelDsymbol::isLabel()		// is this a P_LabelDsymbol()?
{
    return this;
}


/************************ S_AsmStatement ***************************************/

S_AsmStatement::S_AsmStatement(Loc loc, Token *tokens)
    : S_Statement(loc)
{
    this->tokens = tokens;
    asmcode = NULL;
    asmalign = 0;
    refparam = FALSE;
    naked = FALSE;
    regs = 0;
}

S_Statement *S_AsmStatement::syntaxCopy()
{
    return new S_AsmStatement(loc, tokens);
}



int S_AsmStatement::comeFrom()
{
    return TRUE;
}

int S_AsmStatement::blockExit()
{
    // Assume the worst
    return BEfallthru | BEthrow | BEreturn | BEgoto | BEhalt;
}

void S_AsmStatement::toCBuffer(OutBuffer *buf, HdrGenState *hgs)
{
    buf->writestring("asm { ");
    Token *t = tokens;
    while (t)
    {
        buf->writestring(t->toChars());
        if (t->next                         &&
           t->value != LT::TOKmin               &&
           t->value != LT::TOKcomma             &&
           t->next->value != LT::TOKcomma       &&
           t->value != LT::TOKlbracket          &&
           t->next->value != LT::TOKlbracket    &&
           t->next->value != LT::TOKrbracket    &&
           t->value != LT::TOKlparen            &&
           t->next->value != LT::TOKlparen      &&
           t->next->value != LT::TOKrparen      &&
           t->value != LT::TOKdot               &&
           t->next->value != LT::TOKdot)
        {
            buf->writebyte(' ');
        }
        t = t->next;
    }
    buf->writestring("; }");
    buf->writenl();
}

